Skip to content

Instantly share code, notes, and snippets.

@hissy
Last active December 19, 2015 17:58
Show Gist options
  • Save hissy/5995173 to your computer and use it in GitHub Desktop.
Save hissy/5995173 to your computer and use it in GitHub Desktop.
[WordPress] Add AdSense ads to blog sample
<?php
/*
Plugin Name: My AdSense
Description: adsense表示
Author: Takuro Hishikawa
Version: 0.2
Author URI: http://notnil-creative.com/
*/
// add adsbygoogle.js to footer
function script_adsbygoogle() {
echo '<script async src="http://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>';
}
add_action('wp_footer', 'script_adsbygoogle', 100);
// add widget
class My_Adsense_Widget extends WP_Widget {
public function __construct() {
parent::__construct(
'my-adsense-id',
'My AdSense Widget',
array(
'classname' => 'my-adsense-widget'
)
);
}
public function widget( $args, $instance ) {
echo '<ins class="adsbygoogle"
style="margin-bottom:20px;display:inline-block;width:250px;height:250px"
data-ad-client="ca-pub-0000000000000000"
data-ad-slot="0000000000"></ins>';
echo '<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>';
}
}
add_action( 'widgets_init', create_function( '', 'register_widget("My_Adsense_Widget");' ) );
// add ad to content in single after the more anchor
function add_adsense_to_content($content){
$has_more = strpos($content, '<span id="more');
// setup adsense code
$adsense = '';
if ( !wp_is_mobile() && is_singular() ) {
$adsense = '<ins class="adsbygoogle"
style="display:inline-block;width:468px;height:60px"
data-ad-client="ca-pub-0000000000000000"
data-ad-slot="0000000000"></ins>';
} elseif ( wp_is_mobile() && is_singular() ) {
$adsense = '<div style="margin:0 -1.714285714rem 20px -1.714285714rem;text-align:center;width:100%;overflow:hidden;">
<ins class="adsbygoogle"
style="display:inline-block;width:320px;height:50px;margin:0 auto;"
data-ad-client="ca-pub-0000000000000000"
data-ad-slot="0000000000"></ins>
</div>';
}
// add adsense code in content
if ( $adsense != '' ) {
$adsense .= '<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script>';
if ( $has_more !== false) {
$pattern = '/<p><span id\=\"(more\-\d+)"><\/span><\/p>/iu';
$replacement = '<p><span id="$1"></span></p>' . "\n" . $adsense;
$content = preg_replace($pattern, $replacement, $content);
} elseif ( wp_is_mobile() ) {
$content = $adsense . $content;
} elseif ( ! wp_is_mobile() ) {
$content .= $adsense;
}
}
return $content;
}
add_filter('the_content', 'add_adsense_to_content', 10);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment