簡體   English   中英

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. $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. */
?>

這就是我在頁面上顯示內容的方式

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

您可以使用此鈎子過濾所有頁面和帖子的內容,並且僅在條件為true時才返回內容。

只需將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