我已经成功地在我的网站上和我的分类中使用了AJAX。php页面我需要使用offset参数。不幸的是,AJAX造成了偏移量的复杂化,我得到了一遍又一遍的相同帖子。我查阅了WordPress codex,但我不知道如何将解决方案应用于我的特定WP\\U查询。任何能帮助我的人我都会很感激,如果必要的话,我也可以提供更多的代码。谢谢
category.php
<?php
$category = get_category( get_query_var( \'cat\' ) );
$cat_id = $category->cat_ID;
$current_page = max( 1, get_query_var( \'paged\' ) );
$the_query = new WP_Query( array(
\'category__in\' => array($cat_id),
\'post_type\' => \'post\',
\'posts_per_page\' => 5,
\'paged\' => $current_page,
) );
$_SESSION[\'count\'] = 1;
wp_localize_script( \'my_loadmore\', \'misha_loadmore_params\', array(
\'ajaxurl\' => admin_url( \'admin-ajax.php\', \'relative\' ),
\'posts\' => json_encode( $the_query->query_vars ),
\'current_page\' => $current_page,
\'max_page\' => $the_query->max_num_pages
) );
?>
<div id="main" class="container feed-container">
<div class="row mx-auto align-items-center post">
<?php if ($the_query->have_posts()) : ?>
<?php $count = 0; ?>
<?php while ($the_query->have_posts()) : $the_query->the_post(); get_template_part( \'parts/content\', get_post_format() ); ?>
<?php $count++;
$_SESSION[\'count\']=$_SESSION[\'count\']+1;
?>
<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_postdata(); ?>
</div><!-- END ROW -->
</div><!-- END CONTAINER -->
AJAX
jQuery(function($){
var canBeLoaded = true,
bottomOffset = 1300;
$(window).scroll(function(){
if ( misha_loadmore_params.current_page >= misha_loadmore_params.max_page ) {
// console.log( \'max_page reached; AJAX canceled\' );
return;
}
var data = {
\'action\': \'loadmore\',
\'query\': misha_loadmore_params.posts,
\'page\' : misha_loadmore_params.current_page
};
if( $(document).scrollTop() > ( $(document).height() - bottomOffset ) && canBeLoaded == true ){
$.ajax({
url : misha_loadmore_params.ajaxurl,
data: data,
type: \'POST\',
beforeSend: function( xhr ){
canBeLoaded = false;
},
success:function(data){
if( data ) {
$(\'#main\').find(\'div.post:last-of-type\').after( data );
canBeLoaded = true;
misha_loadmore_params.current_page++;
// bottomOffset = ( $( \'#main > div.post:last\' ).offset() || {} ).top
}
}
});
}
});
});
最合适的回答,由SO网友:Sally CJ 整理而成
所以我猜这是this question. 并基于my answer 在那里,您可以使用/添加offset
这样的参数:
输入category.php
, 只需设置首选偏移:
$the_query = new WP_Query( array(
\'category__in\' => array( $cat_id ),
\'post_type\' => \'post\',
\'posts_per_page\' => 5,
\'paged\' => $current_page,
\'offset\' => 1, // set offset
) );
英寸misha_loadmore_ajax_handler()
(处理AJAX请求的PHP函数),在$the_query = new WP_Query( $args );
:if ( isset( $args[\'offset\'] ) ) {
$offset = absint( $args[\'offset\'] );
$args[\'offset\'] = absint( ( $args[\'paged\'] - 1 ) * $args[\'posts_per_page\'] ) + $offset;
}
仅此而已。JavaScript部分无需更改。