I have a ajax request hooked on “template_redirect” (the ajax requests the post’s url), and I want to display only the comment template:
function get_comm(){
if(isset($_GET['get_my_comments'])):
$offset = intval($_GET['get_my_comments']);
echo $offset; // offset will be the same as "cpage"
global $comments, $wp_query, $post, $id;
print_r($comments); // nothing ?
print_r($wp_query->comments); // nothing ??
wp_list_comments('type=comment', $comments); // same :(
exit();
endif;
}
add_action('template_redirect', 'get_comm');
the javascript part works and it’s like this:
$("a.show-more-comments").live("click", function(){
var offset = $(this).attr('rel');
var list = $(this).closest("#comments");
$.ajax({
url: "<?php echo get_permalink($post->ID); ?>",
type: "GET",
data: ({
get_my_comments: offset
}),
success: function(data){
list.append(data);
}
});
});
The problem is that $comments
or $wp_query->comments
don’t seem to be initialized. What am I doing wrong here?
2 Answers
$comments
, or $wp_query->comments
, is initialized by comments_template()
, which you call in your template file when you want to load the comment sub-template file. So at the time of template_redirect
it is not yet initialized. As Chris said, you should call get_comments()
and pass it the post_id
of your current post.
If you’re doing AJAX calls, even not from the admin side, you can use wp-admin/admin-ajax.php
and use special actions hooks. This shortcuts the usual post queries, which you don’t need anyway.