Displaying comments template when serving a single post via ajax in wordpress

I ran into this issue this morning, the comment form wasn’t showing up. I was using a custom comment template and I thought that there might be some issue with the custom template. So I tried with default template but the result was same. After googling for a while, I’ve found the workaround. Here is the solution for you

[sourcecode language=”php”]
//functions.php
add_action("wp_ajax_single", "get_single");
add_action("wp_ajax_nopriv_single", "get_single");

function get_single(){
error_reporting(0); //see later to understand why it is here
global $post;
$post_id = $_REQUEST[‘id’];
if($post_id){
$post = get_post( $post_id);
setup_postdata( $post );
get_template_part( "templates/single");
die();
}
}
[/sourcecode]

The code above registers an ajax callback for accepting GET/POST calls at “/wp-admin/admin-ajax.php?action=single&id=” and display the single post using the template file located at “templates/single.php” in your current theme.

Now, in the “templates/single.php” you must include the following code-block at the top to make sure the comments_template() function work

[sourcecode language=”php”]
global $withcomments;
$withcomments = true;
[/sourcecode]

Anyway, it was also mentioned in the codex like this, but I was confused as I thought it was actually inside the “single display” at first 🙂

Loads the comment template. For use in single Post and Page displays. Will not work outside of single displays unless $withcomments is set to 1.

By the way, that error_reporting(0) line is there to suppress a deprecated notice which says that your theme is missing “comments.php” even if it’s there.

Hope you enjoy this article