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');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 c语言,请帮蒟蒻写一个题的范例作参考
  • ¥15 名为“Product”的列已属于此 DataTable
  • ¥15 安卓adb backup备份应用数据失败
  • ¥15 eclipse运行项目时遇到的问题
  • ¥15 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)