首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WordPress + PHP -如何找出一个记录中是否有更少的段落?

WordPress + PHP -如何找出一个记录中是否有更少的段落?
EN

Stack Overflow用户
提问于 2017-08-21 05:18:39
回答 1查看 29关注 0票数 0

我有这个(痛苦的)脚本:

代码语言:javascript
复制
    /*-----------------------------  3 ---------------------------*/
 $paragraphAfter3 = 3;

*------------------------  WIDGET 3 ----------------------------*/
//Widget Area
add_action( 'widgets_init', 'register_my_widgets_google-ads-3' );
function register_my_widgets_main_google_ads_3(){
  register_sidebar( array(
    /* 'name'          => sprintf(__('Sidebar %d'), $i ), */
    'name'          => 'My code 3',
    /* 'id'            => "sidebar-$i", */
    'id'            => 'google-ads-3',
    'description'   => '',
    'class'         => '',
    'before_widget' => '<div id="%1$s" class="widget %2$s">',
    'after_widget'  => "</div>\n",
    'before_title'  => '<h2 class="google-ads-3 widgettitle">',
    'after_title'   => "</h2>\n",
  ) );
}
add_action( 'widgets_init', 'register_my_widgets_main_google_ads_3' );


/*  function GoogleADS1(){
  if ( function_exists('register_my_widgets_google-ads-1') )
    dynamic_sidebar(google-ads-1);
};  */


add_filter( 'the_content', 'wpse_content_google_ads_3' );

function wpse_content_google_ads_3( $content ) {
if( !is_single() )
return $content;
/*Number paragraf*/
/* $paragraphAfter = 3; //number of paragraph */

global $paragraphAfter3;
$paragraphAfter = $paragraphAfter3; //number of paragraph
$content = explode ( "</p>", $content );
$new_content = '';
for ( $a = 0; 
    $a < count ( $content ); 
    $a ++ ) {
if ( $a == $paragraphAfter ) {
  ob_start();
if ( is_active_sidebar( 'google-ads-3' ) ) :
   dynamic_sidebar( 'google-ads-3' ); 
else :
   echo '<span></span>';
endif;
$result = ob_get_clean();

$new_content .= $result ;
}
  elseif ($a != $paragraphAfter) {
    $new_content .=  '';
}
$new_content .= $content[$a] . "</p>";
}
return $new_content;
}

此脚本通过一定数量的段落插入小部件的内容,并且运行良好。但如果页面上的段落较少。然后,他将小部件的内容粘合到页脚中。如果文章中的段落比文章中显示的少,如何实现不显示小工具?

EN

回答 1

Stack Overflow用户

发布于 2017-08-21 20:03:26

由于您使用的是$content = explode ( "</p>", $content );分解内容,因此循环的最后部分不会有

标记,所以你可以循环到倒数第二个值,就像这样:

代码语言:javascript
复制
for ( $a = 0; $a < count ( $content )-1;  $a ++ ) //**Notice - 1 here**
{
    ...
    ...
}

BUt我的直觉是,你的代码搞乱了DOM,这就是为什么小部件的结果会移到页脚。有一次我看到发生这种情况的例子是if $paragraphAfter = 0。在本例中,小部件的结果被添加到之前,content的第一部分,这可能会弄乱DOM,并使小部件显示在页脚中。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45786893

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档