简体   繁体   English

WordPress的functions.php-如果条件杀死其他帖子内容

[英]Wordpress functions.php - if condition kills other posts content

So I got this code, which I am trying to adapt to my needs. 所以我得到了这段代码,我正在尝试适应我的需求。 It should and does wrap a div around the necessary <img> tags . 它应该并且确实将div包裹在必要的<img> tags周围。 But when I add the " if (is_page...)" all other sites have no content anymore. 但是,当我添加“ if (is_page...)"所有其他站点都没有内容了。 I am very confused as to why this is happening since the code should not execute or do anything when the if statement is not met. 我对为什么会这样感到非常困惑,因为当不满足if语句时,代码不应执行或不执行任何操作。

function breezer_addDivToImage( $content ) {
if ( is_page_template('single.php') ) {
   // A regular expression of what to look for.
   $pattern = '/(<img([^>]*)>)/i';
   // What to replace it with. $1 refers to the content in the first 'capture group', in parentheses above
   $replacement = '<div class="myphoto">$1</div>';

   // run preg_replace() on the $content
   $content = preg_replace( $pattern, $replacement, $content );

   // return the processed content
   return $content;
}
}

add_filter( 'the_content', 'breezer_addDivToImage' );
/* Place custom code above this line. */
?>

This is how i display the content on the page 这就是我在页面上显示内容的方式

<!--S3 show if dynamic page (blogposts)-->
<?php } else if (is_page() == false) {
 if(have_posts()) :
    while(have_posts())  : the_post();
      if ( has_post_thumbnail() ) {
       <img class="responsive-img" src="<?php the_post_thumbnail_url(); ?>">
      <?php } ?>
      <h2><?php the_title(); ?></h2>
      <?php the_content();
        endwhile;
        else : ?>
        <h3></h3>
        <p></p>
 <?php endif;
} ?>
<!--S3 end "show if dynamic page"-->

you filter your content of all pages and posts with this hook and only return the content if the condition is true. 您可以使用此钩子过滤所有页面和帖子的内容,并且仅在条件为true时才返回内容。

Put simply a else {return $content} to your breezer_addDivToImage function. 只需将else {return $ content}放到breezer_addDivToImage函数中即可。

function breezer_addDivToImage( $content ) {
  if ( is_page_template('single.php') ) {
  // A regular expression of what to look for.
  $pattern = '/(<img([^>]*)>)/i';
  // What to replace it with. $1 refers to the content in the first 'capture group', in parentheses above
  $replacement = '<div class="myphoto">$1</div>';

  // run preg_replace() on the $content
  $content = preg_replace( $pattern, $replacement, $content );

  // return the processed content
  return $content;
 }
 else {
  return $content;
 }
}
add_filter( 'the_content', 'breezer_addDivToImage' );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM