Insert HTML after every Nth comment: use the “end-callback” argument

Last Updated on

I did not find any examples of using WordPress’s “end-callback” argument for “wp_list_comments”. It is documented by WordPress here.
Here is an example of how to use it in child-theme code to add custom HTML after each top level comment. This example preserves comment hierarchy, ie: nested replies.

In your child theme directory, create a file called “functions.php”, and add this function “append_html_to_comment” to it.


///////////////////////////////////////
// Show custom HTML every Nth comment.
// "append_html_to_comment" is called as the "end-callback" function in the 
// "wp_lists_comments" call in comments.php
$cc_comment_count = 0;
function append_html_to_comment($comment, $args, $depth) {
	global $cc_comment_count;
	$commentInterval = 5;
	$html = <<<EOD
<!-- Custom HTML goes here. -->
EOD;

    if ( 'div' === $args['style'] ) {
        $tag = 'div';
    } else {
        $tag = 'li';
    }

    echo "</${tag}>";

    $insert = <<<INS
<$tag class="custom-html-after-comment">	
	$html
</$tag>
INS;

    if ($depth === 0) { 
        $cc_comment_count += 1;
        if ($cc_comment_count % $commentInterval == 0) {		
            echo $insert;				
        }		 
    }
}

Copy your theme’s “comments.php” file into your child theme directory.
Specify “append_html_to_comment” as the “end-callback”, as is done below.


<?php
    wp_list_comments( array(
        'style' => 'ol',
        'avatar_size' => 40,
        'end-callback' => 'append_html_to_comment'
    ) );
?>

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.