我使用jquery和php从我的博客卷中获取上一篇文章。我在页面上一次加载一个帖子,然后单击上一个帖子链接以触发ajax调用。 最终结果类似于medium.com如何提取下一篇文章。 下面的代码工作,但是,当我来到最后一篇文章时,它会保持循环并返回一个空值。
这里是jquery部分
loadNextPost : function( callback ) {
$this = this;
$.ajax( {
type: "POST",
url: '/wp-admin/admin-ajax.php',
data: {
action: 'get_prev_post',
current_url: location.href,
nonce: MediumJS.nonce,
}
} )
.done( function( post ) {
if( '' !== post ) {
$this.nextPost = JSON.parse( post );
} else {
$this.nextPost = null;
}
callback.call( $this );
} );
},
现在是php函数
function get_prev_post() {
global $post;
$thispost = url_to_postid($_POST['current_url']);
if ( isset($thispost) ){
$id = (int) $thispost;
$post = get_post( $id );
$attachment_url = wp_get_attachment_url( get_post_thumbnail_id( $previous_post->ID ) );
$previous_post = get_previous_post();
//header( "Content-Type: application/json" );
$array = array('post_id' => $previous_post->ID,'post_content'=> $previous_post->post_content, 'post_title' => $previous_post->post_name, 'permalink' => get_permalink($previous_post->ID), 'attachment_url' => wp_get_attachment_url( get_post_thumbnail_id( $previous_post->ID ) ));
}
echo json_encode($array);
//print_r($thispost);
die();
}