You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在JavaScript中实现WordPress文章循环?

How to Implement a WordPress Post Loop in JavaScript for Dynamic Post Lists

Hey there! If you're looking to display WordPress posts in a dynamic loop using JavaScript, you won't be using the classic PHP while (have_posts()) : the_post(); loop directly—instead, we'll leverage the WordPress REST API to fetch post data and render it with JS. Here's a step-by-step breakdown:

1. Confirm the REST API is Enabled

First, make sure your WordPress site has the REST API active (it's enabled by default in WordPress 4.7+). You can test this by visiting https://your-site-url/wp-json/ in your browser—you should see a JSON response listing available API endpoints.

2. Fetch Posts with JavaScript (Native fetch Example)

We'll use the native fetch API to pull post data from the REST API, then loop through the results to build your post list.

First, add a container in your HTML where the posts will be rendered:

<div id="post-list" class="post-container"></div>

Then add this JavaScript code (you can put it in a script tag or an external JS file):

// Fetch posts from the WordPress REST API
fetch('https://your-site-url/wp-json/wp/v2/posts')
  .then(response => {
    // Check if the request was successful
    if (!response.ok) throw new Error('Failed to fetch posts');
    return response.json();
  })
  .then(posts => {
    const postContainer = document.getElementById('post-list');
    
    // Loop through each fetched post
    posts.forEach(post => {
      // Create a container for individual posts
      const postCard = document.createElement('article');
      postCard.classList.add('post-card');
      
      // Populate the post card with content
      postCard.innerHTML = `
        <h2 class="post-title">
          <a href="${post.link}" target="_blank">${post.title.rendered}</a>
        </h2>
        <div class="post-meta">
          <span class="post-date">${new Date(post.date).toLocaleDateString('en-US', {
            year: 'numeric',
            month: 'long',
            day: 'numeric'
          })}</span>
        </div>
        <div class="post-excerpt">${post.excerpt.rendered}</div>
      `;
      
      // Add the post card to the main container
      postContainer.appendChild(postCard);
    });
  })
  .catch(error => {
    console.error('Error loading posts:', error);
    const postContainer = document.getElementById('post-list');
    postContainer.innerHTML = '<p>Sorry, we couldn\'t load the posts right now.</p>';
  });

3. Customize Your Post Query

You can tweak the API endpoint to filter, sort, or limit posts. Here are some common parameters you can add to the URL:

  • per_page=5: Fetch only 5 posts
  • categories=3: Fetch posts from category ID 3
  • order=asc: Sort posts in ascending date order (oldest first)
  • author=2: Fetch posts by author ID 2

Example of a customized fetch URL:

fetch('https://your-site-url/wp-json/wp/v2/posts?per_page=6&categories=4&order=desc')

4. Include Custom Fields (If Needed)

If you want to display custom post fields, you'll need to expose them to the REST API first. Add this code to your theme's functions.php file:

// Expose custom fields to the WordPress REST API
function add_custom_fields_to_rest_api() {
  register_rest_field('post', 'your_custom_field_key', array(
    'get_callback' => function($post) {
      return get_post_meta($post['id'], 'your_custom_field_key', true);
    },
    'schema' => array(
      'description' => 'A custom field for my posts',
      'type' => 'string'
    )
  ));
}
add_action('rest_api_init', 'add_custom_fields_to_rest_api');

Then you can access the custom field in your JavaScript like this:

// Inside the posts.forEach loop
postCard.innerHTML += `<p class="custom-field">${post.your_custom_field_key}</p>`;

5. Notes to Keep in Mind

  • CORS Issues: If your JS is running on a different domain than your WordPress site, you may need to enable CORS on your WordPress server (you can use a plugin or add headers via .htaccess).
  • Authentication: For private posts or restricted content, you'll need to add authentication (like OAuth or a REST API key) to your fetch request.
  • Performance: Consider adding pagination with the page parameter to avoid loading too many posts at once.

That's it! This approach lets you build dynamic, client-side post loops that update without reloading the page.

内容的提问来源于stack exchange,提问作者Tara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:23:02