我正在尝试使用此教程,但它不起作用:https://artisansweb.net/load-wordpress-post-ajax/
正确的顺序是:4号岗位、1号岗位、3号岗位、2号岗位。前2篇帖子是可以的(单击之前),但当我单击按钮时,结果是错误的(第2篇,第1篇),而不是第3篇,第2篇。
这是我的代码:
页面模板:
<?php /* Template Name: Ajax */
get_header(); ?>
<div class="entry-content">
<?php
$args = array(
\'post_type\' => \'post\',
\'post_status\' => \'publish\',
\'orderby\' => \'date\',
\'order\' => \'DESC\',
\'posts_per_page\' => 2,
\'paged\' => 1
);
$my_posts = new WP_Query($args);
if ($my_posts->have_posts()) {
?>
<div class="my-posts">
<?php while ($my_posts->have_posts()) { $my_posts->the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php the_excerpt(); ?>
<?php } ?>
</div>
<?php } ?>
<button class="loadmore">Load more...</button>
</div>
<script type="text/javascript">
var ajaxurl = "<?php echo admin_url( \'admin-ajax.php\' ); ?>";
var page = 2;
jQuery(\'body\').on(\'click\', \'.loadmore\', function() {
var data = {
\'action\': \'load_posts_by_ajax\',
\'page\': page,
\'security\': \'<?php echo wp_create_nonce("load_more_posts"); ?>\',
\'all_pages\': \'<?php echo $my_posts->max_num_pages; ?>\'
};
jQuery.post(ajaxurl, data, function(response) {
jQuery(\'.my-posts\').append(response);
if(page == data[\'all_pages\']) {
jQuery(\'.loadmore\').fadeOut(400);
}
page++;
});
});
</script>
<?php get_footer(); ?>
功能:
function load_posts_by_ajax_callback() {
check_ajax_referer(\'load_more_posts\', \'security\');
$paged = $_POST[\'page\'];
$args = array(
\'post_type\' => \'post\',
\'post_status\' => \'publish\',
\'orderby\' => \'date\',
\'order\' => \'DESC\',
\'posts_per_page\' => 2,
\'paged\' => $paged
);
$my_posts = new WP_Query($args);
if ($my_posts->have_posts()) {
while ($my_posts->have_posts()) { $my_posts->the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php the_excerpt();
};
};
wp_die();
}
add_action(\'wp_ajax_load_posts_by_ajax\', \'load_posts_by_ajax_callback\');
add_action(\'wp_ajax_nopriv_load_posts_by_ajax\', \'load_posts_by_ajax_callback\');
怎么了?