dpbtbcz6650 2015-04-12 22:28
浏览 79
已采纳

如何在自定义WP_Query Ajax上实现分页

I want to paginate my WordPress posts in a custom loop with Ajax, so when I click on load more button posts will appear.

My code:

<?php 
    $postsPerPage = 3;
    $args = array(
        'post_type' => 'post',
        'posts_per_page' => $postsPerPage,
        'cat' => 1
    );
    $loop = new WP_Query($args);

    while ($loop->have_posts()) : $loop->the_post();
?>
<h1><?php the_title(); ?></h1>
<p>
    <?php the_content(); ?>
</p>
<?php
    endwhile; 
    echo '<a href="#">Load More</a>';
    wp_reset_postdata(); 
?>

This code does not paginate. Is there a better way to do this?

  • 写回答

1条回答 默认 最新

  • dongshengli6384 2015-04-12 23:16
    关注

    The Load More button needs to send a ajax request to the server and the returned data can be added to the existent content using jQuery or plain javascript. Assuming your using jQuery this would starter code.

    Custom Ajax Handler (Client-side)

    <a href="#">Load More</a>
    

    Change to:

    <a id="more_posts" href="#">Load More</a>
    

    Javascript: - Put this at the bottom of the file.

    //</script type="text/javascript">
    
        var ajaxUrl = "<?php echo admin_url('admin-ajax.php')?>";
        var page = 1; // What page we are on.
        var ppp = 3; // Post per page
    
        $("#more_posts").on("click",function(){ // When btn is pressed.
            $("#more_posts").attr("disabled",true); // Disable the button, temp.
            $.post(ajaxUrl, {
                action:"more_post_ajax",
                offset: (page * ppp) + 1,
                ppp: ppp
            }).success(function(posts){
                page++;
                $(".name_of_posts_class").append(posts); // CHANGE THIS!
                $("#more_posts").attr("disabled",false);
            });
    
       });
    
    //</script>
    

    Custom Ajax Handler (Server-side) PHP - Put this in the functions.php file.

    function more_post_ajax(){
        $offset = $_POST["offset"];
        $ppp = $_POST["ppp"];
        header("Content-Type: text/html");
    
        $args = array(
            'post_type' => 'post',
            'posts_per_page' => $ppp,
            'cat' => 1,
            'offset' => $offset,
        );
    
        $loop = new WP_Query($args);
        while ($loop->have_posts()) { $loop->the_post(); 
           the_content();
        }
    
        exit; 
    }
    
    add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax'); 
    add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码
  • ¥50 随机森林与房贷信用风险模型