如何实现一个自定义WP_Query的Ajax分页 [英] How to implement pagination on a custom WP_Query Ajax

查看:151
本文介绍了如何实现一个自定义WP_Query的Ajax分页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想分页我的Word preSS职位与阿贾克斯自定义的循环,所以当我点击加载更多的按钮职位会出现。

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

我的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(); 
?>

这code不分页。有没有更好的方式来做到这一点?

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

推荐答案

加载更多按钮需要发送一个 AJAX 请求到服务器和返回的数据可以被添加到使用jQuery或平原的javascript存在的内容。假设你使用jQuery,这将首发code。

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.

自定义的Ajax处理程序(客户端)

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

更改为:

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

的Javascript:的 - 将这个在文件的底部

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>

自定义的Ajax处理程序(服务器端) PHP 的 - 在functions.php文件将这个

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');

这篇关于如何实现一个自定义WP_Query的Ajax分页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆