首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Wordpress通过按钮点击加载更多帖子

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

Stack Overflow用户
提问于 2016-08-12 03:06:57
回答 1查看 1.6K关注 0票数 0

我是Wordpress的新手。因此,这可能不是最好的方法,甚至不是可能的。话虽如此,我对更好的解决方案持开放态度。

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

我目前拥有的是这样的:

代码语言:javascript
复制
<?php query_posts('showposts=4&offset=12'); ?>
<?php while (have_posts()): the_post(); ?>
    //some html tags
<?php endwhile; ?>

这将加载我的帖子13-16的细节。

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

代码语言:javascript
复制
var offSetCounter = 12;

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

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

提前谢谢。

EN

回答 1

Stack Overflow用户

发布于 2016-08-12 04:43:08

要在Wordpress上运行,请尝试以下命令:

PHP:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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 );
    });
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38904306

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档