Skip to content

Instantly share code, notes, and snippets.

@juslintek
Last active January 7, 2018 19:33
Show Gist options
  • Save juslintek/b144a37ee63861ea544f5d1a457cda93 to your computer and use it in GitHub Desktop.
Save juslintek/b144a37ee63861ea544f5d1a457cda93 to your computer and use it in GitHub Desktop.
Adwords
<?php
add_filter( 'the_content', function ( $content ) {
if ( is_single() && get_post_type() == 'post' ) {
$document = new DiDom\Document( $content, false );
$childElements = $document->find( '.entry-content > p' );
$maxElements = $document->count( '.entry-content > p' ) - 1;
if ($maxElements > 3) {
$randomPosition = rand( 3, $maxElements - 2);
} else {
$randomPosition = rand( 0, $maxElements);
}
ob_start();
?>
<div class="adwords-in-article">
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<ins class="adsbygoogle"
style="display:block; text-align:center;"
data-ad-layout="in-article"
data-ad-format="fluid"
data-ad-client="ca-pub-2404521673534795"
data-ad-slot="1889815335"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
</div>
<?php
$in_article = ob_get_clean();
$wrapper = new \DiDom\Element( 'div', '', [ 'class' => 'adwords-wrapper' ] );
$wrapper->setInnerHtml( $in_article );
if ( ! is_null( $childElements[ $randomPosition ] ) ) {
$childElements[ $randomPosition ]->insertAfter( $wrapper );
}
if ( $document->has( '.adwords-wrapper' ) ) {
$content = $document->html();
}
ob_start();
?>
<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>
<!-- pbad -->
<ins class="adsbygoogle"
style="display:block"
data-ad-client="ca-pub-2404521673534795"
data-ad-slot="8429380947"
data-matched-content-ui-type="image_stacked"
data-matched-content-rows-num="2"
data-matched-content-columns-num="3"
data-ad-format="autorelaxed"></ins>
<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>
<?php
return $content . ob_get_clean();
}
return $content;
}, 50 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment