【问题标题】:Wordpress Custom Excerpt for Blog Posts博客文章的 Wordpress 自定义摘录
【发布时间】:2016-11-21 13:12:20
【问题描述】:

我正在尝试将此自定义摘录添加到博客帖子中,以便它从帖子中获取前 35 个字符并将其作为摘录。但是,该代码适用于所有帖子类型,甚至是自定义帖子类型。

如何仅将此自定义摘录仅应用于博客文章?我尝试将下面的代码包装在以下条件中 - 这是默认博客文章页面设置的内容 - 但没有奏效。

if(is_page_template('template-blog-list.php')) {

    function custom_excerpts($content = false) {
        global $post;

        $content        = wp_strip_all_tags($post->post_content);
        $excerpt_length = 35;
        $words          = explode(' ', $content, $excerpt_length + 1);

        if(count($words) > $excerpt_length) :
            array_pop($words);
            array_push($words, '...');
            $content = implode(' ', $words);
        endif;

        $content = $content . '<br><br><a class="more-button" href="'.  get_permalink($post->ID) . '">Read More</a>';

        return $content;
    }
    add_filter('get_the_excerpt', 'custom_excerpts');
}

【问题讨论】:

    标签: wordpress custom-post-type


    【解决方案1】:

    您可以查看$post-&gt;post_type:

    if ( $post->post_type !== 'post' ) {
        return $content;
    }
    

    global $post 行之后添加这一行。

    【讨论】:

      【解决方案2】:
          <?php 
          function custom_excerpts($content = false) {
          global $post;
          $content = wp_strip_all_tags($post->post_content);
          $excerpt_length = 35;
          $words = explode(' ', $content, $excerpt_length + 1);
       if(is_blog ()) :
          if(count($words) > $excerpt_length) :
              array_pop($words);
              array_push($words, '...');
              $content = implode(' ', $words);
          endif;
          endif;
          $content = $content . '<br><br><a class="more-button" href="'.  get_permalink($post->ID) . '">Read More</a>';
      
          return $content;
      }
      
      add_filter('get_the_excerpt', 'custom_excerpts');
          function is_blog () {
              return ( is_archive() || is_author() || is_category() || is_home() || is_single() || is_tag()) && 'post' == get_post_type();
          }
          ?>
      

      is_blog () 检查是否是页面博客,并根据返回 $content

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-11-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多