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

Wordpress:如何根据参数获得不同的摘录长度,wordpress,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); 有什么

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);

有什么想法吗?谢谢

据我所知,使用_extract()无法做到这一点

还有一个类似的问题

我发现要做的唯一一件事就是编写一个新函数来代替_extract()。将下面代码的一些变体放入functions.php中,并调用limit_content($yourLength),而不是_extract()

function limit\u content($content\u length=250,$allowtags=true,$allowedtags=''){
全球$员额;
$content=$post->post\u内容;
$content=apply_过滤器('the_content',$content);
如果(!$allowtags){
$allowedtags.='';
$content=strip_标签($content$allowedtags);
}
$wordarray=explode(“”,$content,$content\u length+1);
if(计数($wordarray)>$content\u长度){
数组_pop($wordarray);
数组推送($wordarray,“…”);
$content=内爆(“”,$wordarray);
$content.=“

”; } echo$内容; }
(功能学分:)


还有一些“高级摘录”插件,提供类似这样的功能,您可以查看。

谢谢您的回答,thaddeusmt

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


嗯,再回答我一次,这个解决办法其实很小。据我所知,不可能将参数传递给函数my_extract_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');
然后,在调用循环中的摘录之前,请为$MyExcerpletLength指定一个值(如果希望为其余文章指定默认值,请不要忘记将其设置回0):


/* 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');
function my_excerpt_length() {
global $myExcerptLength;

if ($myExcerptLength) {
    return $myExcerptLength;
} else {
    return 80; //default value
    }
}
add_filter('excerpt_length', 'my_excerpt_length');
<?php
    $myExcerptLength=35;
    echo get_the_excerpt();
    $myExcerptLength=0;
?>