Last active
February 21, 2025 18:17
-
-
Save birgire/493f0d646491532e0ed5b0c5549f1a12 to your computer and use it in GitHub Desktop.
Inject Ads To WordPress Comments - See https://wordpress.stackexchange.com/a/328155/26350
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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