loading posts via ajax and jquery in wordpress -
i'm using jquery , php previous post blog roll. i'm loading 1 post @ time on page , clicking previous post link trigger ajax call. end result similar how medium.com pulls next post article. below code works, somewhat, however, keeps looping , returning null value when come last post.
here's jquery part
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 ); } ); },
now php function
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(); }
Comments
Post a Comment