Wordpress通过按钮点击加载更多帖子

时间:2016-08-11 19:06:57

标签: php jquery wordpress

我对Wordpress相对较新。所以这可能不是最好的方法,甚至可能。话虽如此,我愿意接受更好的解决方案。

我有一个显示最新12个帖子的主页。 我想制作一个按钮,点击它将加载下一个4。

我现在所拥有的是:

<?php query_posts('showposts=4&offset=12'); ?>
<?php while (have_posts()): the_post(); ?>
    //some html tags
<?php endwhile; ?>

这将加载我13-16号的详细信息。

我正在寻找一种方法,我可以把它放在一个函数中,然后通过jquery click()事件调用它,我可以使用某种计数器来计算偏移量。

之类的东西
var offSetCounter = 12;

$(".btnLoadMore").click(function(){
    //php function call
    loadmore(offSetCounter);
    offSetCounter += 4;
});

因此,下次单击按钮时,offSetCounter将为16,依此类推。

先谢谢。

1 个答案:

答案 0 :(得分:0)

要在Wordpress上运行,请尝试以下操作:

PHP:

add_action( 'wp_ajax_nopriv_show_next_posts',  'show_next_posts' );
function show_next_posts() {
    $offset = $_POST['offset']; 
    $the_query = new  new WP_Query( array( 'posts_per_page' => 4, 'offset' => $offset ) );



    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        echo '<div class="post_container">' . get_the_title() . '</div>';
    }
    wp_reset_postdata();
    wp_die();
    return;
}

add_action('wp_head','add_ajaxurl');
function add_ajaxurl() {
     $ajaxurl =  admin_url('admin-ajax.php');
     echo '<script type="text/javascript">
        var ajaxurl ='.$ajaxurl.';
     </script>';

}

JS:

jQuery('.btnLoadMore').click(function(){
    var offset = jQuery('.post_container').length();
    var data = {
        'action': 'show_next_posts',
        'offset': offset
    };

    jQuery.post(ajaxurl, data, function( response ) {
        console.log( response );
    });
});
相关问题