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

Jor*_*rge 0 wordpress

wordpress中的摘录长度默认为55个字.

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

function new_excerpt_length($length) {
    return 20;
}
add_filter('excerpt_length', 'new_excerpt_length');
Run Code Online (Sandbox Code Playgroud)

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

the_excerpt();
Run Code Online (Sandbox Code Playgroud)

但我无法弄清楚我怎么能添加一个参数来获得不同的长度,以便我可以调用,例如:

the_excerpt(20);

the_excerpt(34);
Run Code Online (Sandbox Code Playgroud)

有任何想法吗?谢谢!

Jor*_*rge 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');
Run Code Online (Sandbox Code Playgroud)

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

<?php
    $myExcerptLength=35;
    echo get_the_excerpt();
    $myExcerptLength=0;
?>
Run Code Online (Sandbox Code Playgroud)