我希望在我的wordpress博客上的每个帖子的第6段之后显示一段javascript。到目前为止,我只能在使用固定变量时才能使用该函数:
add_filter( 'the_content', 'prefix_insert_post_ads' );
function prefix_insert_post_ads( $content ) {
$ad_code = 'fixed variable such as <div>box</div>';
if (is_single()) {
return prefix_insert_after_paragraph( $ad_code, 6, $content );
}
return $content;
}
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 );
}
我想添加的javascript:
function ad_unit() ?>
<script type="text/javascript">
ad = document.getElementById('marker');
if (ad.getBoundingClientRect().width) {
adWidth = ad.getBoundingClientRect().width;
} else {
adWidth = ad.offsetWidth; // for old IE
}
/* Choose the right ID */
if ( adWidth >= 600 )
aId = ["test1"];
else if ( adWidth >= 468 )
aId = ["test2"];
else
aId = ["test3"];
document.write (
'<div id="' + akId[0] + '"></div>'
);
</script>
<?php
我试图声明$ placeholder = ad_unit();但它继续在内容的顶部显示单位,而不是在第6段之后。不知何故,我添加javascript函数后,prefix_insert_after段落功能不起作用。有什么想法吗?
答案 0 :(得分:1)
function ad_unit()
{
ob_start();
?>
<script type="text/javascript">
ad = document.getElementById('marker');
if (ad.getBoundingClientRect().width) {
adWidth = ad.getBoundingClientRect().width;
} else {
adWidth = ad.offsetWidth; // for old IE
}
/* Choose the right ID */
if ( adWidth >= 600 )
aId = ["test1"];
else if ( adWidth >= 468 )
aId = ["test2"];
else
aId = ["test3"];
document.write ('<div id="' + akId[0] + '"></div>');
</script>
<?php
return ob_get_clean();
}
因此,使用ob_start()
启用输出缓冲会发生什么。您输出HTML但缓冲它,然后使用ob_get_clean()
从输出缓冲区获得缓冲输出。
如果没有函数,这将更干净(并且肯定有效,我不记得在放入PHP函数时HTML的简单做法):
// Somewhere above the rest of your application
ob_start(); ?>
/// YOUR HTML/javascript
<?php
$advertisement = ob_get_clean();
答案 1 :(得分:0)
你需要为php函数打开和关闭括号
<?php
function ad_unit() { ?>
<script type="text/javascript">
ad = document.getElementById('marker');
if (ad.getBoundingClientRect().width) {
adWidth = ad.getBoundingClientRect().width;
} else {
adWidth = ad.offsetWidth; // for old IE
}
/* Choose the right ID */
if ( adWidth >= 600 )
aId = ["test1"];
else if ( adWidth >= 468 )
aId = ["test2"];
else
aId = ["test3"];
document.write (
'<div id="' + akId[0] + '"></div>'
);
</script>
<?php }