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?
$comments
, or$wp_query->comments
, is initialized bycomments_template()
, which you call in your template file when you want to load the comment sub-template file. So at the time oftemplate_redirect
it is not yet initialized. As Chris said, you should callget_comments()
and pass it thepost_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.I use this function to render templates when using ajax
render() is a custom function to load a certain template. But essentially you will need to retrieve the comments yourself to add to the list.
Use get_comments (http://codex.wordpress.org/Function_Reference/get_comments) or do a direct query and then you can either render a template as above or build the html with a php function.
I use the global $data to hod anything I want to render in the template.