如何使用过滤功能在内容前后添加广告,每个广告都有其优先级。如何在函数中使用参数,然后在过滤器中使用参数这是函数
function mywp_before_after($content) {
if(is_page() || is_single()) {
$beforecontent = \'This goes before the content. Isn\\\'t that awesome!\';
$aftercontent = \'And this will come after, so that you can remind them of something, like following you on Facebook for instance.\';
$fullcontent = $beforecontent . $content . $aftercontent;
} else {
$fullcontent = $content;
}
return $fullcontent;
}
add_filter(\'the_content\', \'mywp_before_after\');
需要
function mywp_before_after($content,$place,$priority) {
if ($place ==\'before\'):
$fullcontent = $beforecontent . $content;
else:
$fullcontent =$content . $aftercontent;
}
add_filter(\'the_content\', \'mywp_before_after\',10,2,$place,$priority);
最合适的回答,由SO网友:WPExplorer 整理而成
您需要对每个播发使用add\\u filter(),以便相应地设置优先级。示例:
// Ad 1
function myprefix_ad_1( $content ) {
$ad = \'Your ad code\';
return $ad_1 . $content; // this one is before
}
add_filter( \'the_content\', \'myprefix_ad_1\', 10 );
// Ad 2
function myprefix_ad_2( $content ) {
$ad = \'Your ad code\';
return $content . $ad; // This one is after
}
add_filter( \'the_content\', \'myprefix_ad_2\', 20 );
SO网友:WPExplorer
实际上,这里有一种更高级的方法,你可以使用它将你的广告存储在一个循环中,然后通过循环添加你的过滤器。这是很酷的东西;)
function myprefix_ads() {
return array(
\'ad-1\' => array(
\'priority\' => 10,
\'content\' => \'Ad for pages before\',
\'placement\' => \'before\',
\'condition\' => \'is_page\'
),
\'ad-2\' => array(
\'priority\' => 10,
\'content\' => \'Add for posts after\',
\'placement\' => \'after\',
\'condition\' => \'is_single\'
)
);
}
$ads = myprefix_ads();
foreach ( $ads as $key => $val ) {
add_filter( \'the_content\', function( $content ) use ( $val ) {
if ( isset( $val[\'condition\'] ) && ! call_user_func( $val[\'condition\'] ) ) {
return $content;
}
if ( \'before\' == $val[\'placement\'] ) {
$content = $val[\'content\'] . $content;
} elseif ( \'after\' == $val[\'placement\'] ) {
$content = $content . $val[\'content\'];
}
return $content;
}, $val[\'priority\'] );
}