Getting $comments outside the comment template

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:

Read More
   $("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?

Related posts

Leave a Reply

2 comments

  1. $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.

  2. I use this function to render templates when using ajax

    function ajax_render( $template ) {
    
    global $data, $posts, $post, $wp_did_header, $wp_did_template_redirect, $wp_query, $wp_rewrite, $wpdb, $wp_version, $wp, $id, $comment,  $user_ID;
    
    ob_start();
    render($template);
    $response = array('text' => ob_get_clean());
    echo json_encode($response);
    exit;
    }
    

    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.