Theend-callback 属于wp_list_comments()
一种方法是使用
end-callback 中的参数:
wp_list_comments( [ 
    \'end-callback\' => \'wpse_comments_ads_injection\',
    ... other arguments ...
], $comments );
 除了你的另一半
wp_list_comments 参数,通过定义:
function wpse_comments_ads_injection( $comment, $args, $depth ) {
     static $instance = 0;
     $tag             = ( \'div\' == $args[\'style\'] ) ? \'div\' : \'li\';
     echo "</{$tag}><!-- #comment-## -->\\n";
     if ( 0 === $instance % 2 ) {
         echo "<{$tag} class=\\"comment__ad\\">YOUR AD HERE!</{$tag}>";
     }
     $instance++;
}
 我们用静态变量进行计数
$instance 每次通话都会递增。
这应该插入定义的评论广告,使用div 或li 标记,具体取决于样式。
通过使用结束回调,我们不需要修改注释回调,如果不需要,只需插入广告即可。因此,如果我们需要默认的注释布局,我们也可以通过这种方式插入广告。
还可以使用注释depth 控制广告显示。
请注意callback 和end-callback 属于wp_list_comments(), 有三个输入参数,而不是四个。
Thewp_list_comments_args 然后,我们可以进一步调整过滤器并使用wp_list_comments_args 过滤器:
add_filter( \'wp_list_comments_args\', function( $args ) {
    if ( ! isset( $args[\'end-callback\'] ) ) {
        $args[\'end-callback\'] = \'wpse_comments_ads_injection\';
    }
    return $args;
} );
 而不是修改
wp_list_comments() 直接地
我们可以为此创建插件或将其添加到functions.php 当前主题目录中的文件。
引入注入的偏移量、速率和html,然后我们可以添加对注入的速率、偏移量和html的支持:
add_filter( \'wp_list_comments_args\', function( $args ) {
    if ( ! isset( $args[\'end-callback\'] ) ) {
        // Modify this to your needs!
        $args[\'end-callback\'] = \'wpse_comments_ads_injection\';
        $args[\'_ads_offset\']  = 0;  // Start injecting after the 1st comment.
        $args[\'_ads_rate\']    = 2;  // Inject after every second comment.
        $args[\'_ads_html\']    = \'<img src="http://placekitten.com/g/500/100" />\';
    }
    return $args;
} );
 其中,我们通过以下方式调整结束回调:
/**
 * Inject Ads To WordPress Comments - end-callback for wp_list_comments().
 *
 * The Ads HTML is sanitized through wp_kses_post().
 *
 * @version 1.0.11
 * @see https://wordpress.stackexchange.com/a/328155/26350
 */
function wpse_comments_ads_injection( $comment, $args, $depth ) {
    static $instance = 0;
    $tag             = ( \'div\' == $args[\'style\'] ) ? \'div\' : \'li\';
    $ads_rate        = isset( $args[\'_ads_rate\' ] ) && $args[\'_ads_rate\' ] > 0 
        ? (int) $args[\'_ads_rate\' ] 
        : 2;
    $ads_offset      = isset( $args[\'_ads_offset\' ] ) && $args[\'_ads_offset\' ] > 0
            ? (int) $args[\'_ads_offset\' ]
        : 0;
    $ads_html        = isset( $args[\'_ads_html\' ] ) 
        ? wp_kses_post( $args[\'_ads_html\' ] )
        : \'\';
    echo "</{$tag}><!-- #comment-## -->\\n";
    if ( $ads_offset <= $instance && 0 === ( $instance - $ads_offset ) % $ads_rate && ! empty( $ads_html ) ) {
        echo "<{$tag} class=\\"comment__ad\\">{$ads_html}</{$tag}>";
    }
    $instance++;
}
 这里有一个
gist 用于将代码添加到
functions.php 当前主题目录中的文件。
这是未经测试的,但我希望您可以根据需要进行调整!