Skip to content

Instantly share code, notes, and snippets.

@birgire

birgire/functions.php

Last active Feb 9, 2019
Embed
What would you like to do?
Inject Ads To WordPress Comments - See https://wordpress.stackexchange.com/a/328155/26350
/**
* 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++;
}
/**
* Filter wp_comments_list().
*
* @see https://wordpress.stackexchange.com/a/328155/26350
*/
add_filter( 'wp_list_comments_args', function( $args ) {
if ( ! isset( $args['end-callback'] ) ) {
// Modify 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" />'; // HTML for the AD.
}
return $args;
} );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.