我正在尝试在自己的网站中实现this。
我想在自定义WP_Query的底部显示一个阅读更多按钮,然后单击它,将其加载到下面的下一组内容中。
链接的示例中的一半代码有效,因为它获取正确的帖子数,并更新“阅读更多”按钮的数据属性,在命中全部数时将其隐藏,但是在单击时,它不会添加任何内容内容...多余的帖子不会按原样显示在div中。
JS控制台中没有错误,也看不到任何错误。
这是添加到我的page-work.php模板文件中的代码:
<div id="smartmaps" class="smartmaps col xs-col-14 xs-offset-1 md-col-12 md-offset-2">
<?php
//Find out how many posts
$total_posts = wp_count_posts('smart_maps');
$total_posts = $total_posts->publish;
$number_shown = 0;
global $post;
$the_offset = trim( sanitize_text_field( wp_unslash( $_POST['pOffset'] ) ) );
$the_total = trim( sanitize_text_field( wp_unslash( $_POST['totalPosts'] ) ) );
$args = array( 'post_type' => 'smart_maps', 'posts_per_page' => 2, 'offset' => $the_offset );
$posts_shown = $the_offset;
$the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<div class="single-smartmap col xs-col-8">
<div class="col xs-col-4">
<img src="/wp-content/uploads/2018/12/group-4@2x.png" class="circle">
</div>
<div class="col xs-col-10 xs-offset-1">
<h5 class="smart-map-title"><?php the_title();?></h5>
<div class="block-icons">
<span class="icon-heart"></span>
<span class="icon-plant"></span>
<span class="icon-cup"></span>
<span class="icon-book"></span>
</div>
</div>
</div>
<?php $posts_shown++; $number_shown++;
endwhile;
if ( $posts_shown >= $the_total ) { ?>
<div id="all-posts-shown"></div>
<?php } ?>
<?php if ( $number_shown < $total_posts ) { ?>
<div class="loadMore" data-offset="<?php echo $number_shown; ?>" data-total="<?php echo $total_posts; ?>">
Load More
</div>
<?php } endif; ?>
</div>
JS AJAX:
jQuery(function($) {
$('.loadMore').click(function() {
//get the offset
var postOffset = $(this).attr('data-offset');
var totalPosts = $(this).attr('data-total');
var thisObj = $(this);
//get Page Template and put on page
var ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
$.ajax({
type: 'POST',
url: ajax_url,
data: {
action: 'get_loadmore',
pOffset: postOffset,
totalPosts: totalPosts,
},
dataType: "html",
success: function(data) {
$('#smartmaps').append(data);
$new_offset = parseInt ( thisObj.attr('data-offset') ) + 2;
thisObj.attr('data-offset', $new_offset) //set the new post offset.
if ( $('#all-posts-shown')[0] ) {
thisObj.slideUp(); //hide loadmore if all posts have been displayed.
}
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert("error");
}
});
}); //end of click function
});
并将代码添加到我的functions.php
//Load More Button
add_action('wp_ajax_get_loadmore', 'get_loadmore');
add_action( 'wp_ajax_nopriv_get_loadmore', 'get_loadmore' );
function get_loadmore() {
include(get_template_directory().'/page-work.php');
wp_die();
}
侧面注意:不确定是否重要...该页面上将包含3个单独的WP_Query,均带有自己的Read More按钮,并引入不同的帖子类型。