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

Wordpress functions.php - if condition kills other posts content

所以我得到了这段代码,我正在努力适应我的需要。它应该并且确实将 div 包裹在必要的 <img> tags 周围。但是当我添加“if (is_page...)" 所有其他站点都不再有内容时。我很困惑为什么会发生这种情况,因为当不满足 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.  refers to the content in the first 'capture group', in parentheses above
   $replacement = '<div class="myphoto"></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. */
?>

这是我在页面上显示内容的方式

<!--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"-->

您使用此挂钩过滤所有页面和帖子的内容,如果条件为真,则仅 return 内容。

只需将 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.  refers to the content in the first 'capture group', in parentheses above
  $replacement = '<div class="myphoto"></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' );