Wordpress:如何根据参数获取不同的摘录长度

时间:2010-08-28 18:23:52

标签: wordpress

默认情况下,wordpress中的摘录长度为55个字。

我可以使用以下代码修改此值:

function new_excerpt_length($length) {
    return 20;
}
add_filter('excerpt_length', 'new_excerpt_length');

因此,以下调用只返回20个字:

the_excerpt();

但我无法弄清楚如何添加参数以获得不同的长度,以便我可以调用,例如:

the_excerpt(20);

the_excerpt(34);

有什么想法吗?谢谢!

3 个答案:

答案 0 :(得分:7)

嗯,再次回答我,解决方案实际上非常简单。据我所知,将参数传递给函数my_excerpt_length()是不可能的(除非你想修改wordpress的核心代码),但是可以使用全局变量。所以,你可以在你的functions.php文件中添加这样的东西:

function my_excerpt_length() {
global $myExcerptLength;

if ($myExcerptLength) {
    return $myExcerptLength;
} else {
    return 80; //default value
    }
}
add_filter('excerpt_length', 'my_excerpt_length');

然后,在循环中调用摘录之前,为$ myExcerptLength指定一个值(如果你想拥有其余帖子的默认值,不要忘记将其设置为0):

<?php
    $myExcerptLength=35;
    echo get_the_excerpt();
    $myExcerptLength=0;
?>

答案 1 :(得分:1)

就我发现使用the_excerpt()而言,没有办法做到这一点。

有类似的StackOverflow问题here

我唯一要做的就是编写一个新函数来获取the_excerpt()的位置。将下面代码的一些变体放入 functions.php 并调用limit_content($ yourLength)而不是the_excerpt()。

function limit_content($content_length = 250, $allowtags = true, $allowedtags = '') {
    global $post;
    $content = $post->post_content;
    $content = apply_filters('the_content', $content);
    if (!$allowtags){
        $allowedtags .= '<style>';
        $content = strip_tags($content, $allowedtags);
    }
    $wordarray = explode(' ', $content, $content_length + 1);
    if(count($wordarray) > $content_length) {
        array_pop($wordarray);
        array_push($wordarray, '...');
        $content = implode(' ', $wordarray);
        $content .= "</p>";
    }
    echo $content;
}

(功能信用:fusedthought.com

还有“高级摘录”插件,提供您可以检查的功能。

答案 2 :(得分:0)

感谢您的回答,thaddeusmt。

我最终实现了以下解决方案,根据类别和计数器提供不同的长度($myCounter是循环中的计数器)

/* Custom length for the_excerpt */ 
function my_excerpt_length($length) {
    global $myCounter;

    if (is_home()) {
        return 80;
    } else if(is_archive()) {
        if ($myCounter==1) {
            return 60;
        } else {
            return 25;
        }
    } else {
        return 80;
    }
}
add_filter('excerpt_length', 'my_excerpt_length');
相关问题