所以我正在构建wordpress插件,并且尝试为我的自定义帖子类型简码添加ajax加载更多按钮。但是我真的无法解决。它不断重复加载相同的数据。这是我的简码:
public function list($atts) {
$loop_args = array(
'orderby' => 'post__in date',
'order' => 'DESC',
'post_type' => 'listing',
'posts_per_page' => $atts['limit'],
);
$loop = new WP_Query($loop_args);
ob_start();
?>
<div class="listings-wrapper">
<div class="js-filter container <?php echo $single_cas; ?>">
<div class="list-items">
<?php
while ($loop->have_posts()) :
$loop->the_post();
include LISTINGS_BASE_DIR . 'templates/shortcodes/list-toplist.php';
// End the loop.
endwhile;
?>
</div>
</div>
<?php
if ($loop->max_num_pages > 1)
echo '<div class="more-posts">Load more</div>';
?>
</div>
<?php
// Restore original post
wp_reset_postdata();
return ob_get_clean();
}
}
在这里我本地化ajax脚本:
public function enqueue_scripts()
{
// For load more button
wp_enqueue_script('ajax-loadmore', plugin_dir_url(__FILE__) . 'js/myloadmore.js', array('jquery'), $this->version, false);
wp_localize_script('ajax-loadmore', 'wp_ajax_object', array('ajax_url' => admin_url('admin-ajax.php')));
}
这是加载更多功能:
<?php
add_action('wp_ajax_nopriv_more_listings_ajax', 'more_listings_ajax');
add_action('wp_ajax_more_listings_ajax', 'more_listings_ajax');
function more_listings_ajax()
{
$offset = $_REQUEST["offset"];
$loop_args = array(
'post_type' => 'listing',
'status' => 'publish',
'posts_per_page' => 1,
'order' => 'ASC',
'offset' => $offset,
);
$loop = new WP_Query($loop_args);
while ($loop->have_posts()) :
$loop->the_post();
include LISTINGS_BASE_DIR . 'templates/shortcodes/list-toplist.php';
// End the loop.
endwhile;
wp_reset_postdata();
die();
}
这是我的ajax脚本:
(function ($) {
$(document).ready(function () {
$(".more-posts").on("click", function (e) {
e.preventDefault();
offset = 1;
$.ajax({
// use the ajax object url
url: wp_ajax_object.ajax_url,
data: {
action: "more_listings_ajax",
offset: offset
},
success: function (data) {
offset++;
$('.list-items').append(data);
},
error: function (data) {
// test to see what you get back on error
console.log(data);
}
});
});
});
})(jQuery);
我被困在这里,任何帮助都会得到帮助。谢谢