First of all you need to register a action callback for you ajax request.
Secondly you need to send all ajax request to wp-admin/admin-ajax.php
(both GET
and POST
).
And lastly you need to modify your javascript a little to pass the action
parameter which will trigger the callback. and var post_link = $(this);
doesn’t gives the post id from rel attribute you should use var post_link = $(this).attr("rel");
You can get the ajax url by admin_url( 'admin-ajax.php' );
in your theme. and use javascript localization to get inside your js.
Everything else looks good on your index.php
Example
JavaScript
$(document).ready(function(){
$.ajaxSetup({cache:false});
$(".post-link").click(function(){
var post_id = $(this).attr("rel");
$("#post-container").html("loading...");
//$("#post-container").load(post_link+"?action=load_more_post&pid="+post_id);
// update: .load() should send request to ajax url not the post url
$("#post-container").load(ajax_url+"?action=load_more_post&pid="+post_id);
return false;
});
});
PHP (in your theme’s function.php)
add_action( 'wp_ajax_load_more_post', 'load_more_post_callback' );
add_action( 'wp_ajax_nopriv_load_more_post', 'load_more_post_callback' );
function load_more_post_callback() {
if( isset($_GET["pid"]) ){
$post = get_post( $_GET["pid"] );
if( $post instanceof WP_Post ) {
echo '<h1 class="post_title">'.$post->post_title.'</h1>';
} else {
// nothing found with the post id
}
} else {
// no post id
}
wp_die();
}