基于模板调整摘录页面(_E)

时间:2016-08-06 作者:Darren Bachan

如何写入要调整的条件the_excerpt 在不同的页面上?

例如,在我的page-products.php 我想要的页面the_excerpt 就这么说吧40.

function custom_excerpt_length( $length ) {
    return 20;
}
add_filter( \'excerpt_length\', \'custom_excerpt_length\', 999 );
是吗ifelse 实现这一目标的条件?

1 个回复
SO网友:Bryan Willis

You can add it straight to the template before the header in most cases...

<?php /* Template Name: Products */ ?>
<?php 
  add_filter( \'excerpt_length\', function( $length ) {  return 10; }, 999);
  get_header(); 
?>
如果你更愿意加入functions.php:

Method 2: In the loop

$slug = get_page_template_slug($post->ID);
if(\'page-products.php\' == $slug) {
        add_filter( \'excerpt_length\', function( $length ) { 
           return 20; 
        }, 999);    
}
if ( is_page_template( \'page-products.php\' ) ) {
    add_filter( \'excerpt_length\', function( $length ) { 
       return 20; 
    }, 999);
}

This could also be used to get the template....

global $post;
$template = get_post_meta($post->ID,\'_wp_page_template\',true);

Or possibly even this (untested):

add_action(\'get_header\', function() {
    if ( is_page( array( 37, \'Products\' ) ) ) {
        add_filter( \'excerpt_length\', function( $length ) { 
           return 20; 
        }, 999);
    }
}, 1);

Or as seen here, you can create your own function to allow the excerpt length to be determined on a need to need basis by the amount of characters.

function excerpt($limit) {
  $excerpt = explode(\' \', get_the_excerpt(), $limit);
  if (count($excerpt)>=$limit) {
    array_pop($excerpt);
    $excerpt = implode(" ",$excerpt).\' ...\';
  } else {
    $excerpt = implode(" ",$excerpt);
  } 
  $excerpt = preg_replace(\'`\\[[^\\]]*\\]`\',\'\',$excerpt);
  return $excerpt;
}
要显示的内容:

<?php echo excerpt(50); ?>

相关推荐

Strip div From Excerpt

我在特定页面中有\\u extract(),我需要去掉一个div并保留文本,但只保留在该页面的摘录中。我相信我需要创建一个带有自定义摘录的函数,但我不知道该怎么做。测试了我在这里找到的几种解决方案,但没有任何效果。