WordPress的加载更多发布通过按钮点击
问题描述:
我是相对较新的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等等。
在此先感谢。
答
要在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);
});
});
是什么loadmore(offSetCounter)呢? – stweb
希望这将是一个自定义php函数,将调用第一个块中的代码 – Radizzt
在您的js/JQuery代码中,您只能启动对php的ajax请求,但不能php本身。 – stweb