根据标题长度更改摘录长度

时间:2013-07-25 11:52:19

标签: php wordpress

在WordPress中,是否可以根据标题的长度更改摘录长度?

我只是简单地称呼标题:

<?php the_title(); ?>

摘录:

 <?php html5wp_excerpt('html5wp_index'); // in my functions.php I set the length ?>

的functions.php

function html5wp_index($length);
{
    return 25;

}

因此,如果标题是15个字符,那么摘录只会是10个例子吗?

1 个答案:

答案 0 :(得分:2)

这应该可以帮到你。只需将它放在functions.php文件中即可。目前它会影响正在使用the_excerpt();的所有帖子或页面,但您可以将其包装在条件中以隔离它。只需阅读代码中的注释,即可进一步解释正在发生的事情。

<?php

function aw_new_excerpt_length($length) {

    // get the post title and find its string length
    $str = get_the_title();
    $titleLength = strlen($str);

    // check if length is longer that 10 characters
    // and return an excerpt length for more or 
    // less than 10
    if($titleLength > 10) {
    return 5;
    } else {
        return 3;
    }
}

// then add the filter to change the excerpt length
add_filter('excerpt_length', 'aw_new_excerpt_length');

?>

只需更改数字即可将其设置为您的规格。

相关问题