2016-11-21 128 views
2

我试图将这个自定义摘录添加到博客文章,以便它抓住帖子的前35个字符,并使该摘录。但是,该代码适用于所有帖子类型,甚至自定义帖子类型。博客文章的WordPress自定义摘录

我该如何只将此自定义摘录仅应用于博客文章?我试图在下面的条件中包装下面的代码 - 这是默认的博客文章页面设置为 - 但没有工作。

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'); 
} 

回答

1

你可以只检查$post->post_type

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

global $post行添加此行。

+0

非常好 - 简短而亲切。谢谢。 – optimus203

-1
<?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

+0

这将工作相同 –