2 回答
TA贡献1851条经验 获得超3个赞
您的代码中可能存在一些问题,请尝试以下代码。请根据您的代码更改条件并检查它是否有效。
你的模板.php
<div id="ajax-posts" class="row">
<?php get_header(); ?>
<?php
$args = array(
'post_type' => 'business',
'paged' => 1,
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<div class="content">
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
</div>
<?php
endwhile;
wp_reset_postdata();
?>
</div>
<p class="para"></p>
<button id="more_posts">Load More</button>
脚本.js
var pageNumber = 2;
jQuery(function($) {
$('body').on('click', '#more_posts', function load_posts(){
var str = '&pageNumber=' + pageNumber + '&action=more_post_ajax';
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function(data){
var $data = $(data);
if($data.length){
$("#ajax-posts").append($data);
$("#more_posts").attr("disabled",false);
} else{
$(".para").text("No More Posts");
$("#more_posts").attr("disabled",true);
}
pageNumber++;
},
error : function(jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
});
});
函数.php
<?php
add_action('wp_enqueue_scripts', 'myscripts');
function myscripts() {
wp_register_script('functions', get_template_directory_uri() .'/script.js');
wp_localize_script( 'functions', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
));
wp_enqueue_script('functions');
}
if (isset($_REQUEST['posts_per_page'])) {
$pageCount = $_REQUEST['posts_per_page'];
$wp_query->set("posts_per_page", $pageCount);
$wp_query->get_posts();
}
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
function more_post_ajax(){
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
$args = array(
'post_type' => 'competition',
'paged' => $page,
);
$loop = new WP_Query($args);
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
?>
<h2><?php the_title() ?></h2>
<?php the_excerpt() ?>
<?php
endwhile;
endif;
wp_reset_postdata();
}
?>
- 2 回答
- 0 关注
- 130 浏览
添加回答
举报