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

如何在WordPress的AJAX加载更多功能中传递文章类型参数

Reusing WordPress AJAX Load More for Multiple Post Types

Great question! Reusing your AJAX-powered load-more functionality across different post types is straightforward, and the cleanest approach is to pass the post_type parameter directly in your AJAX request data. Let’s break down how to adjust your existing code to make this work smoothly.


Step 1: Pass Post Type from the Frontend

First, add flexibility by storing the target post type directly on your load-more button using a data-post-type attribute. This lets you reuse the same button for any post type:

<!-- For standard blog posts -->
<button class="load-more" data-post-type="post">Load More Posts</button>

<!-- For a custom post type (e.g., "portfolio" items) -->
<button class="load-more" data-post-type="portfolio">Load More Portfolio Items</button>

Then update your AJAX code to pull this value and include it in the request payload:

// Grab the post type from the button's data attribute
var post_type = load_more.data('post-type');

$.ajax({ 
    type: "POST", 
    dataType: "json", 
    url: ajax_get_posts_object.ajax_url, 
    data: { 
        action: "ajax_get_posts", 
        security: ajax_get_posts_object.ajax_nonce, 
        current_page: next_page, 
        categories: $selectedCategories, 
        tags: $selectedTags, 
        post_type: post_type // Add this line to send the post type to PHP
    }, 
    // ... rest of your existing AJAX logic (beforeSend, success, error handlers)
});

If you’re working on a page dedicated to a single post type (like a custom post type archive), you could hardcode the post_type value instead—but the data attribute approach gives you maximum reusability across your site.


Step 2: Receive and Validate the Post Type in PHP

Next, update your ajax_get_posts PHP function to safely handle the post_type parameter, validate it for security, and use it in your WP_Query:

function ajax_get_posts() {
    // First, verify the nonce to prevent unauthorized requests
    if (!wp_verify_nonce($_POST['security'], 'ajax_get_posts_nonce')) {
        wp_send_json_error('Invalid security token');
    }

    // Get the post type from the request, default to 'post' if not provided
    $post_type = isset($_POST['post_type']) ? sanitize_text_field($_POST['post_type']) : 'post';

    // Validate that the post type actually exists (blocks malicious input)
    if (!post_type_exists($post_type)) {
        wp_send_json_error('Invalid post type');
    }

    // Build your query arguments with the dynamic post type
    $paged = isset($_POST['current_page']) ? intval($_POST['current_page']) : 1;
    $args = array(
        'post_type'      => $post_type, // Use the passed post type here
        'post_status'    => 'publish',
        'paged'          => $paged,
        'posts_per_page' => 6, // Adjust to your preferred per-page count
        // Keep your existing filter logic
        'category__in'   => isset($_POST['categories']) ? array_map('intval', $_POST['categories']) : array(),
        'tag__in'        => isset($_POST['tags']) ? array_map('intval', $_POST['tags']) : array(),
    );

    $query = new WP_Query($args);

    // Rest of your existing code to format posts into a JSON response...
    $posts_data = array();
    if ($query->have_posts()) {
        while ($query->have_posts()) {
            $query->the_post();
            // Populate $posts_data with post details (title, permalink, thumbnail, etc.)
        }
    }
    wp_reset_postdata();

    wp_send_json_success(array(
        'posts' => $posts_data,
        'pages' => $query->max_num_pages,
        'post_count' => $query->found_posts
    ));
}
add_action('wp_ajax_ajax_get_posts', 'ajax_get_posts');
add_action('wp_ajax_nopriv_ajax_get_posts', 'ajax_get_posts');

Key Notes & Security Tips

  • Sanitize & Validate: Always sanitize user input (we use sanitize_text_field() for post_type) and validate that the post type exists with post_type_exists()—this stops malicious requests in their tracks.
  • Custom Taxonomies: If your custom post types use custom taxonomies instead of default categories/tags, you can extend this pattern to pass a taxonomy parameter from the frontend too, then adjust your WP_Query args accordingly.
  • Full Reusability: With this setup, you can use the exact same load-more button and AJAX function for any post type on your site—just update the data-post-type attribute on the button.

内容的提问来源于stack exchange,提问作者Jesse Luke Orange

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:35:48