Reputation: 5846
I am trying to load page content in wordpress when clicking on a nav item. The aim is to refresh the contents of #content
with the requested data.
Here is my Nav
$sidebar_posts = query_posts( 'post_type=page&order=ASC' );
echo '<ul id="sidebar-ajax">';
foreach($sidebar_posts as $post){
echo '<li id="' .get_the_ID(). '">';
echo '<a class="ajax-click" href="#">'.get_the_title().'</a>';
echo '</li>';
}
echo '</ul>';
Here is my Function
add_action ( 'wp_ajax_nopriv_load-content', 'my_load_ajax_content' );
function my_load_ajax_content () {
$post_id = $_POST[ 'post_id' ];
$post = get_post( $post_id, OBJECT);
$response = apply_filters( 'the_content', $post->post_title );
echo $response;
die(1);
}
wp_enqueue_script( 'my-ajax-request', get_bloginfo('template_directory') . '/js/ajax.js', array( 'jquery' ) );
wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
Here is my JS
jQuery(document).ready(function($) {
$(".ajax-click").click(function() {
$("#loading-animation").show();
var post_id = $(this).parent("li").attr("id");
var ajaxURL = MyAjax.ajaxurl;
$.ajax({
type: 'POST',
url: ajaxURL,
data: {"action": "load-content", post_id: post_id },
success: function(response) {
$("#content").html(response);
$("#loading-animation").hide();
alert(post_id);
return false;
}
});
});
});
When selecting a nav item, the alert shows with the correct post_id
, but $response
returns as 0.
Any ideas what the issue could be?
Upvotes: 3
Views: 1924
Reputation: 766
Are you loged in wordpress while testing? If YES try adding
add_action ( 'wp_ajax_load-content', 'my_load_ajax_content' );
just after your
add_action ( 'wp_ajax_nopriv_load-content', 'my_load_ajax_content' );
Wordpres has to hooks for guests and loged users.
Upvotes: 3