我有一个网站,我需要控制显示的摘录长度。有些帖子可能有手动摘录,因此我无法使用excerpt_length
滤器
我当然可以用一些substr()
, 但正在寻找一种更优雅的解决方案(如果存在的话)。
我有一个网站,我需要控制显示的摘录长度。有些帖子可能有手动摘录,因此我无法使用excerpt_length
滤器
我当然可以用一些substr()
, 但正在寻找一种更优雅的解决方案(如果存在的话)。
看看我的答案:Best Collection of Code for your functions.php file
如果我正确理解了你的问题,它会满足你的要求。
将此放入functions.php
:
function excerpt($num) {
$limit = $num+1;
$excerpt = explode(\' \', get_the_excerpt(), $limit);
array_pop($excerpt);
$excerpt = implode(" ",$excerpt)."... (<a href=\'" .get_permalink($post->ID) ." \'>Read more</a>)";
echo $excerpt;
}
然后,在主题中,使用代码<?php excerpt(\'22\'); ?>
将摘录限制为22个字符。:)
使用recent version 在Wordpress(v.3.3.0+)中,您实际上可以使用wp_trim_words
.
function excerpt($limit) {
return wp_trim_words(get_the_excerpt(), $limit);
}
另请参见:https://stackoverflow.com/a/17177847/851045我想说的是,看看core是如何做到的:http://phpxref.ftwr.co.uk/wordpress/wp-includes/formatting.php.source.html#l1840
为了便于复制和粘贴,我冒昧地将代码放在这里。
global $post;
if( empty($post->post_excerpt) ){
$text = apply_filters( \'the_excerpt\', get_the_excerpt() );
} else {
$text = $post->post_excerpt;
$text = strip_shortcodes( $text );
$text = apply_filters(\'the_content\', $text);
$text = str_replace(\']]>\', \']]>\', $text);
$text = strip_tags($text);
$excerpt_length = apply_filters(\'excerpt_length\', 55);
$excerpt_more = apply_filters(\'excerpt_more\', \' \' . \'[...]\');
$words = preg_split("/[\\n\\r\\t ]+/", $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY);
if ( count($words) > $excerpt_length ) {
array_pop($words);
$text = implode(\' \', $words);
$text = $text . $excerpt_more;
} else {
$text = implode(\' \', $words);
}
}
简单地说,可以按以下方式进行。
function custom_excerpt_length( $length ) {
return 20;
}
add_filter( \'excerpt_length\', \'custom_excerpt_length\', 999 );
参考号:Codex尝试以下方法:您可以使用过滤器“extract\\u length”控制摘录输出的字数下面是几个示例,说明如何根据不同的条件控制大小
add_filter( \'excerpt_length\', \'new_excerpt_length\' );
function new_excerpt_length( $more ) {
if(is_front_page()){
if(has_post_thumbnail()){
return 15;
} else {
return 45;
}
} else {
return 100;
}
}
编辑:该死,我刚刚注意到你说过滤方法是不可行的。哦,好吧,这是给那些通过谷歌来到这里,然后想要这个的人的。在您的functions.php
/* easy excerpt limitation
*/
function
easy_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;
}
和使用echo easy excerpt(mylimit)
而不是the_excerpt()
<它工作得很好。