【发布时间】:2014-03-20 05:49:04
【问题描述】:
我想在第一段之后或之前将广告代码插入 WordPress 帖子(详细信息页面)。像this post 有没有任何插件或任何想法..
【问题讨论】:
标签: wordpress
我想在第一段之后或之前将广告代码插入 WordPress 帖子(详细信息页面)。像this post 有没有任何插件或任何想法..
【问题讨论】:
标签: wordpress
你可以试试插件Ad Inserter。
或者使用这个WPBeginner tutorial的例子:
<?php
//Insert ads after second paragraph of single post content.
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code = '<div>Ads code goes here</div>';
if ( is_single() && ! is_admin() ) {
return prefix_insert_after_paragraph( $ad_code, 2, $content );
}
return $content;
}
// Parent Function that makes the magic happen
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
}
return implode( '', $paragraphs );
}
【讨论】:
这是在 WordPress 帖子内容中随机显示广告的代码-
//Insert ads between first and fourth paragraph of single post content to show it randomly between first and second paragraph.
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
// Add code for mobile
$ad_code_mobile = 'AD CODE FOR MOBILE';
// Add code for PC
$ad_code_pc = 'AD CODE FOR PC/DESKTOP/LAPTOP';
if ( is_single() && ! is_admin() ) {
if (!wp_is_mobile()) {
$randnumpc = mt_rand(1,4);
return prefix_insert_after_paragraph( $ad_code_pc, $randnumpc, $content );
}
else {
$randnummobi = mt_rand(1,4);
return prefix_insert_after_paragraph( $ad_code_mobile, $randnummobi, $content );
}
}
return $content;
}
// Parent Function that makes the magic happen
function prefix_insert_after_paragraph( $insertion, $paragraph_id, $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $insertion;
}
}
return implode( '', $paragraphs );
}
该代码将在第 1 段和第 4 段中随机显示广告。您可以将此代码放在主题的 functions.php 末尾,也可以为此创建单独的插件。
来源:https://www.eyeswift.com/random-ad-code-in-wordpress-post-content-without-plugin/
【讨论】: