这是我的帖子循环:
<?php
$query_masonry = new WP_Query(array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 3
));
if ($query_masonry->have_posts()) :
while ($query_masonry->have_posts() ) : $query_masonry->the_post();
get_template_part( 'content', get_post_format() );
endwhile;
else :
get_template_part( 'content', 'none' );
endif;
wp_reset_postdata();
?>
在下面,我有这个:
<button id="load-more">Load more</button>
[只需单击“加载更多”按钮,我如何再用ajax加载3个帖子?
我尝试了很多插件,但未成功。有人帮我吗?
我想更新我的代码,使用提取api加载ajax:
PHP code:
// Enqueue script.
wp_enqueue_script( 'ajax-load-post' );
wp_localize_script(
'ajax-load-post',
'ajax_load_post_data',
array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'ajax_nonce' => wp_create_nonce( 'ajax_load_post' ),
)
);
// Ajax handle.
add_action( 'wp_ajax_load_post', 'ajax_load_post' );
add_action( 'wp_ajax_nopriv_load_post', 'ajax_load_post' );
function ajax_load_post() {
check_ajax_referer( 'ajax_load_post', 'ajax_nonce' );
$post_query = new WP_Query(
array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 3,
)
);
ob_start();
if ( $post_query->have_posts() ) {
while ( $post_query->have_posts() ) {
$post_query->the_post();
echo get_the_title() . '<br>';
}
} else {
echo 'No posts found!';
}
$response['content'] = ob_get_clean();
wp_send_json_success( $response );
}
JS code:
// In js file.
document.addEventListener(
'load',
function() {
var data = {
action: 'load_post',
ajax_nonce: ajax_load_post_data.ajax_nonce,
};
data = new URLSearchParams( data ).toString();
var request = new Request(
ajax_load_post_data.ajax_url,
{
method: 'POST',
body: data,
credentials: 'same-origin',
headers: new Headers(
{
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
}
)
}
);
fetch( request )
.then(
function( res ) {
if ( 200 !== res.status ) {
console.log( 'Status Code: ' + res.status );
throw res;
}
return res.json();
}
).then(
function( json ) {
if ( ! json.success ) {
return;
}
console.log( 'Json data:', json.data );
}
).catch(
function( err ) {
console.log( err );
}
).finally(
function() {
console.log( 'All Done!' );
}
);
}
);