WordPressテーマにSWELLを使用しているサイトで記事タイトル上にアドセンス広告を表示するには、アクションフックswell_before_post_headを使用する。
add_action('swell_before_post_head', function($post_id) {
echo do_shortcode('[[blog_parts id="xxxx"]]');
});
なお、このPHPにてアドセンス広告を使用するには、該当ブログパーツのidを指定する必要がある。やることは以下。
- ブログパーツのタイトルを適当に決める。
- カスタムHTMLブロックを挿入。
- 使用するアドセンスのディスプレイ広告のコードを貼り付け。
- 保存。
- 作成したブログパーツのidを、先ほどのPHPのblog_parts id=”xxxx”で指定。
PHPが用意できたので、続いて表示するブログパーツを調整するCSSを追加する。デフォルトのmargin-bottomは4em、paddingは左右16pxであることに注意。
.single
.l-mainContent__inner>.p-blogParts.post_content:first-child {
margin-bottom: 2em;
padding: 0;
}
これで記事タイトル上にアドセンス広告を表示できる。
SPで非表示にしたい場合は以下。
add_action('swell_before_post_head', function($post_id) {
echo '<div class="custom-content">' .
do_shortcode('[[blog_parts id="xxxx"]]') .
'</div>';
});
/* コンテンツの調整 */
.single
.l-mainContent__inner
.custom-content
.p-blogParts.post_content:first-child {
margin-bottom: 2em;
padding: 0;
}
/* SP・タブレットで非表示 */
@media (max-width: 1024px) {
.custom-content {
display: none;
}
}