WordPress的:如何根据参数获得不同的摘录长度
问题描述:
默认情况下wordpress中摘录的长度是55个字。WordPress的:如何根据参数获得不同的摘录长度
我可以用下面的代码修改这个值:
function new_excerpt_length($length) {
return 20;
}
add_filter('excerpt_length', 'new_excerpt_length');
所以,下面的调用将返回刚刚20个字:
the_excerpt();
但我想不通,我怎么能添加一个参数,以获得不同的长度,以便我可以打电话,例如:
the_excerpt(20);
the_excerpt(34);
任何想法?谢谢!
答
嗯,再回答我,该解决方案实际上是相当微不足道。据我所知,不可能将参数传递给函数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;
?>
答
就我发现使用the_excerpt()而言,没有办法做到这一点。
还有一个类似的*问题here。
我发现要做的唯一事情就是写一个新的函数来获取这个表达式的地方。将以下代码的一些变体放入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)
也有“先进摘录”插件提供的功能这样就可以查询到。
答
感谢您的回答,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');
这仅仅是为我工作的代码...谢谢! – 2013-09-20 12:49:22