“有限”;_except”;WordPress环境中的文本


Limited "the_excerpt" text within a WordPress environment

通过研究,我发现这个问题已经被问了很多次,但我的例子有点不同。我试图用以下elseif:为预先存在的客户环境添加字符限制

elseif(get_post_type() == 'post') {
    echo '<p class="excerpt">';
        the_excerpt();
    echo '</p>';
}

我试图通过函数使用几个方法,但是,我一直找不到解决方案。我本身不是PHP开发人员,所以我在这里学习,希望其他开发人员能够帮助解决这个问题,并简要描述未来如何处理这个问题。

谢谢!

p.S.-我阅读了此处的文档:http://codex.wordpress.org/Conditional_Tags并且无法在不破坏else语句其余部分的情况下使其工作。

默认情况下,摘录长度设置为55个单词。要使用extract_length过滤器将摘录长度更改为20个单词,请将以下代码添加到主题中的functions.php文件中:

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

http://codex.wordpress.org/Function_Reference/the_excerpt

使用get_the_excerpt返回文本而不打印,并使用substr:将其剪切为所需长度

elseif(get_post_type() == 'post') {
    echo '<p class="excerpt">';
    $excerpt = get_the_excerpt();
    $limit = 100;
    if (strlen($excerpt) > $limit) {
        echo substr($excerpt, 0, $limit), '[...]';
    } else {
        echo $excerpt;
    }
    echo '</p>';
}

有很多方法可以做到这一点。

简易方法:

安装Advanced Except插件,将the_excerpt();替换为the_advanced_excerpt(),并根据需要在管理面板的Settings->Except中进行配置(或在函数调用中使用字符串查询vars)。这也可以让你做很多事情,比如自定义"阅读更多"链接(或排除它),添加"…"或者在末尾的一些其他文本,剥去或允许特定的html标签,等等

繁琐的方式:

您可以将substr PHP函数(docs)与get_the_content();get_the_excerpt()结合使用,将其修剪为任意数量的字符(或对其执行任何其他操作),就像freejosh的答案一样。

高级/清洁方式:

使用Srikanth答案中描述的方法将摘录长度过滤为您想要的字符数(这是我的首选方式,除非您需要一些高级摘录选项,如use_words等)。