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

WordPress自定义文章类型AJAX加载更多功能失效求助

问题描述

尝试为自定义文章类型magazine实现AJAX加载更多功能,支持按分类数组筛选特定/全部文章,无更多文章时给用户提示。但目前点击「Load More」按钮后,函数仅循环却不返回3篇更多文章。

已完成的开发步骤

第一步:页面模板taxonomy-magazine-category.php

用于展示初始3篇文章,点击加载更多按钮每次返回3篇直至加载完毕:

<div class="post row">

    <?php
    $paged = ( get_query_var('page') ) ? get_query_var('page') : 1;
    $latests = new WP_Query(array(
    'posts_per_page' => 3,
    'post_type' => 'magazine',
    ));

    while($latests->have_posts()): $latests->the_post();    //put the post card here ?>
        <div class="col-12 col-sm-12 col-md-7 col-xl-9">

                <div class="blog-article-cards list-articles">
                    <?php
                        get_template_part('/components/magazine-article-card', null, array( 'magazines' => $magazines[$i], 'style' => 'regular'));
                 ?>
                </div>
        </div>
     <?php  endwhile; ?>

</div>

<script>
    var limit = 3,
        page = 1,
        type = 'latest',
        category = '',
        max_pages_latest = <?php echo $latests->max_num_pages ?>
</script>
<?php if ( $latests->max_num_pages > 1 ){
    echo '<div class="load_more text-center">
                    <a href="#" class="btn btn-circle btn-inverse btn-load-more">Load More</a> 
                </div>';
} else { ?>
    <article>
        <h1>Sorry...</h1>
        <p><?php _e('Sorry, No Posts Available !'); ?></p>
    </article>

<?php } wp_reset_query(); ?>



<?php get_footer(); ?>

第二步:子主题functions.php添加AJAX处理函数

加载AJAX文件并处理请求:

function bsubash_load_more_scripts() {
    wp_enqueue_script('jquery');
    wp_register_script( 'loadmore_script', get_stylesheet_directory_uri() . '/js/ajax.js', array('jquery') );
    wp_localize_script( 'loadmore_script', 'loadmore_params', array(
        'ajaxurl' => admin_url('admin-ajax.php'),
    ) );

    wp_enqueue_script( 'loadmore_script' );
}

add_action( 'wp_enqueue_scripts','bsubash_load_more_scripts' );


function bsubash_loadmore_ajax_handler(){
    $type = $_POST['type'];
    $category = isset($_POST['category']) ? $_POST['category']: '';
    $args['paged'] = $_POST['page'] + 1;
    $args['post_status'] = 'publish';
    $args['posts_per_page'] =  $_POST['limit'];
    if($type == 'archive'){
        $args['category_name'] = $category;
    }
    query_posts( $args );
    if( have_posts() ) :
        while(have_posts()): the_post();
//write your single post card
            the_title();
            the_excerpt();
        endwhile;
    endif;
    die;
}
add_action('wp_ajax_loadmore','bsubash_loadmore_ajax_handler');
add_action('wp_ajax_nopriv_loadmore','bsubash_loadmore_ajax_handler');

第三步:AJAX交互文件js/ajax.js

处理按钮点击和AJAX请求:

jQuery(function($) {
    $('.btn-load-more').click(function(e) {
        e.preventDefault();
        var button = $(this),
            data = {
                'action': 'loadmore',
                'limit': limit,
                'page': page,
                'type': type,
                'category': category
            };

        $.ajax({
            url: loadmore_params.ajaxurl,
            data: data,
            type: 'POST',
            beforeSend: function(xhr) {
                button.text('Loading...'); // change the button text, you can also add a preloader image
            },
            success: function(data) {
                if (data) {
                    $(".latest_posts_wrapper").append(data);
                    page++;
                    button.text('Load More');
                    if (page == max_pages_latest)
                        button.remove(); // if last page, remove the button
                } else {
                    button.remove(); // if no data, remove the button as well
                }
            }
        });
    });

});

额外代码:页面模板顶部的特色文章获取(不影响当前问题)

$magazines = [];

$wp_query = new WP_Query(
    array(
        'post_type' => 'Magazine',
        'tax_query' => array(
            array (
                'taxonomy' => 'magazine_categories',
                'field' => $categoryId,
                'terms' => $category,
                'posts_per_page' => $postsPerPage,
            )
        ),
    )
);

while ($wp_query->have_posts()) : $wp_query->the_post();

    //$blogProxy = new BlogProxy(get_the_ID());
    $magazine = new Magazine();
    $magazine->title = get_the_title();
    $magazine->featured_image = get_the_post_thumbnail_url(get_the_ID());
    $magazine->preview_text = get_the_excerpt();
    $magazine->permalink = get_the_permalink();
    $magazine->date = get_the_date();

    array_push($magazines, $magazine);

endwhile;

wp_reset_postdata();

?>

问题排查与修复方案

1. AJAX查询未指定自定义文章类型

AJAX处理函数中未设置post_type为magazine,默认仅查询普通文章,导致返回空结果。同时自定义分类需用tax_query而非默认category_name参数。

修复代码:

function bsubash_loadmore_ajax_handler(){
    $type = $_POST['type'];
    $category = isset($_POST['category']) ? $_POST['category']: '';
    $args['paged'] = $_POST['page'] + 1;
    $args['post_status'] = 'publish';
    $args['posts_per_page'] =  $_POST['limit'];
    $args['post_type'] = 'magazine'; // 指定自定义文章类型
    
    if($type == 'archive' && !empty($category)){
        // 使用自定义分类的tax_query
        $args['tax_query'] = array(
            array(
                'taxonomy' => 'magazine_categories',
                'field' => 'slug', // 根据实际情况调整为term_id或slug
                'terms' => $category
            )
        );
    }
    
    // 替换query_posts为WP_Query,避免干扰全局查询
    $query = new WP_Query($args);
    if( $query->have_posts() ) :
        while($query->have_posts()): $query->the_post();
            // 和页面模板保持一致,调用文章卡片组件
            get_template_part('/components/magazine-article-card', null, array( 
                'magazines' => (object)array(
                    'title' => get_the_title(),
                    'featured_image' => get_the_post_thumbnail_url(),
                    'preview_text' => get_the_excerpt(),
                    'permalink' => get_the_permalink(),
                    'date' => get_the_date()
                ), 
                'style' => 'regular'
            ));
        endwhile;
    endif;
    wp_reset_postdata(); // 重置查询状态
    die;
}

2. JS目标容器选择器不匹配

页面模板中的文章容器是.post.row,但JS中使用.latest_posts_wrapper,导致返回内容无法追加到正确位置。

修复JS代码:

// 替换原选择器
$(".post.row").append(data);

3. 初始分页参数错误

页面模板初始查询使用get_query_var('page'),自定义查询应使用paged参数;同时JS初始page值需与初始查询分页同步,且需传递当前分类slug。

修复页面模板中的查询与JS变量:

// 初始查询部分
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$latests = new WP_Query(array(
    'posts_per_page' => 3,
    'post_type' => 'magazine',
    'paged' => $paged // 添加分页参数
));

// JS变量部分
<script>
    var limit = 3,
        page = <?php echo $paged ?>, // 同步初始分页值
        type = 'latest',
        category = '<?php echo get_queried_object()->slug; ?>', // 传递当前分类slug
        max_pages_latest = <?php echo $latests->max_num_pages ?>
</script>

4. 初始循环中$magazines[$i]未定义

页面模板循环中使用的$magazines[$i]未初始化,且与当前查询无关,需直接传递当前文章的信息给组件。

修复页面模板循环:

while($latests->have_posts()): $latests->the_post(); ?>
    <div class="col-12 col-sm-12 col-md-7 col-xl-9">
        <div class="blog-article-cards list-articles">
            <?php
                get_template_part('/components/magazine-article-card', null, array( 
                    'magazines' => (object)array(
                        'title' => get_the_title(),
                        'featured_image' => get_the_post_thumbnail_url(),
                        'preview_text' => get_the_excerpt(),
                        'permalink' => get_the_permalink(),
                        'date' => get_the_date()
                    ), 
                    'style' => 'regular'
                ));
             ?>
        </div>
    </div>
 <?php endwhile; ?>

5. 无更多文章提示缺失

当前JS直接移除按钮,需添加用户提示:

success: function(data) {
    if (data) {
        $(".post.row").append(data);
        page++;
        button.text('Load More');
        if (page == max_pages_latest) {
            button.replaceWith('<p class="no-more-posts text-center">没有更多文章了</p>');
        }
    } else {
        button.replaceWith('<p class="no-more-posts text-center">没有更多文章了</p>');
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.04 22:35:28