Wordpress:如何根据参数获取不同的摘录长度 [英] Wordpress: How to obtain different excerpt lengths depending on a parameter
问题描述
wordpress 中的摘录长度默认为 55 个字.
The length of the excerpt in wordpress is 55 words by default.
我可以用下面的代码修改这个值:
I can modify this value with the following code:
function new_excerpt_length($length) {
return 20;
}
add_filter('excerpt_length', 'new_excerpt_length');
因此,以下调用将仅返回 20 个单词:
So, the following call will return just 20 words:
the_excerpt();
但是我不知道如何添加一个参数来获取不同的长度,以便我可以调用,例如:
But I can't figure out how could I add a parameter to obtain different lengths, so that I could call, for example:
the_excerpt(20);
the_excerpt(34);
有什么想法吗?谢谢!
推荐答案
嗯,再次回答我,解决方案其实很琐碎.据我所知,将参数传递给函数 my_excerpt_length() 是不可能的(除非你想修改 wordpress 的核心代码),但可以使用全局变量.所以,你可以在你的functions.php文件中添加这样的东西:
uhm, answering me again, the solution was actually quite trivial. it's not possible, as far as i know, to pass a parameter to the function my_excerpt_length() (unless you want to modify the core code of wordpress), but it is possible to use a global variable. so, you can add something like this to your functions.php file:
function my_excerpt_length() {
global $myExcerptLength;
if ($myExcerptLength) {
return $myExcerptLength;
} else {
return 80; //default value
}
}
add_filter('excerpt_length', 'my_excerpt_length');
然后,在循环内调用摘录之前,您为 $myExcerptLength 指定一个值(如果您想为其余帖子使用默认值,请不要忘记将其重新设置为 0):>
And then, before calling the excerpt within the loop, you specify a value for $myExcerptLength (don't forget to set it back to 0 if you want to have the default value for the rest of your posts):
<?php
$myExcerptLength=35;
echo get_the_excerpt();
$myExcerptLength=0;
?>
这篇关于Wordpress:如何根据参数获取不同的摘录长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!