How to place comments_template(); outside the loop?

ok, after some research I came up with the solution. The solution is for displaying wordpress comments outside the loop and as a bonus how to place disqus comments outside the loop as well.

First, How to place wordpress comments outside the loop:

In single.php we need to define a new global variable for storing the post id (place this inside the loop)

global $postid;
$postid = get_the_ID();

Then, we can place the list of comments outside the loop with the following code:

<ol class="commentlist">
    <?php    
        //Gather comments for a specific page/post 
        $comments = get_comments(array(
            'post_id' => $postid,
            'status' => 'approve' //Change this to the type of comments to be displayed
        ));

        //Display the list of comments
        wp_list_comments(array(
            'per_page' => 10, //Allow comment pagination
            'reverse_top_level' => false //Show the latest comments at the top of the list
        ), $comments);

    ?>
</ol>

You can as well place the comment form and pass the post id as follows:

<?php comment_form( $args, $postid ); ?>

For DISQUS:

In single.php, We need to define a second variable to get the post title (place this inside the loop):

global $dposttitle;
$dposttitle = wp_title( '', false);

And then add the following call wherever you want to display your disqus comments:

In your child’s theme functions add the following:

function disqus_embed($disqus_shortname, $postid, $dposttitle) {
    global $post;
    wp_enqueue_script('disqus_embed','http://'.$disqus_shortname.'.disqus.com/embed.js');
    echo '<div id="disqus_thread"></div>
    <script type="text/javascript">
        var disqus_shortname = "'.$disqus_shortname.'";
        var disqus_title = "'.$dposttitle.'";
        var disqus_url = "'.get_permalink($postid).'";
        var disqus_identifier = "'.$disqus_shortname.'-'.$postid.'";
    </script>';
}

Finally, call disqus_embed outside the loop in single.php

disqus_embed($disqus_shortname, $postid, $dposttitle);

Please feel free to tell me if there is a better way to implement this.

Leave a Comment