一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

wordrpess the_excerpt()函数截取字符无效

时间:2014-04-03 编辑:简简单单 来源:一聚教程网

具体如下:

 代码如下 复制代码

/**
 * Display the post excerpt.
 *
 * @since 0.71
 * @uses apply_filters() Calls 'the_excerpt' hook on post excerpt.
 */
function the_excerpt() {
        echo apply_filters('the_excerpt', get_the_excerpt());
}

/**
 * Retrieve the post excerpt.
 *
 * @since 0.71
 *
 * @param mixed $deprecated Not used.
 * @return string
 */
function get_the_excerpt( $deprecated = '' ) {
        if ( !empty( $deprecated ) )
                _deprecated_argument( __FUNCTION__, '2.3' );

        $post = get_post();

        if ( post_password_required() ) {
                return __( 'There is no excerpt because this is a protected post.' );
        }

        return apply_filters( 'get_the_excerpt', $post->post_excerpt );
}

如果你仔细研究过,就会发现get_the_excerpt和the_excpert都是以抓取文章在数据库中的post_excerpt字段来实现的,而当这个字段(也就是在后台没有填写摘要时)为空,则会执行filter来调整和控制输出的长度与内容。

如果你在开发中发现,怎么都不能让the_excerpt显示出原本的形式,你打算自己通过字符串截取等方法来代替这个函数的时候,不妨试试下面这段代码:

 代码如下 复制代码
if(has_excerpt())the_excerpt();else{
 $length = apply_filters('excerpt_length',20);
 echo apply_filters('the_excerpt',wp_trim_words($post->post_content,$length));
}

看上去极其简单的几行代码,却包含了很多我们以往没有接触过的知识。

首先,apply_filters的运用很少有人做到娴熟。例如我们希望让文章按照WordPress的输出格式输出时,我们可以使用

echo apply_filters('the_content','你的HTML代码')
来代替,这一招几乎被90%的开发者忽略,甚至很多人根本不知道这种用法。

其次,wp_trim_words是最长被忽视的函数,我们老是希望截取一段特定字符串长度的文字,结果根本不知道WordPress早就准备好了这样的函数出来。

热门栏目