php theexcerpt,WordPress获取文章摘要函数the_excerpt、get_the_excerpt

重要:本文最后更新于2018-12-25 09:10:21,某些文章具有时效性,若有错误或已失效,请在下方留言或联系代码狗。

文章摘要不仅对于网站的SEO是非常重要,而且对网页的排版提升用户体验也很重要。WordPress给我们提供了两个获取文章摘要的函数the_excerpt与get_the_excerpt,可以让我们轻易的得到文章摘要数据。如果不使用摘要,试想如果的文章列表将整篇文章显示出来,用户得翻多久才能看到下一篇文章呢?下面是WordPress获取摘要函数的构成使用详解。

函数描述

the_excerpt:显示文章摘要。

get_the_excerpt:检索文章摘要。

函数原型

the_excerpt与get_the_excerpt函数都位于wp-includes/post-template.php文件中。

function the_excerpt() {

/**

* Filters the displayed post excerpt.

*

* @since 0.71

*

* @see get_the_excerpt()

*

* @param string $post_excerpt The post excerpt.

*/

echo apply_filters( 'the_excerpt', get_the_excerpt() );

}

不用说,从函数构成上可以看出,the_excerpt函数是用get_the_excerpt函数构成的,下面是get_the_excerpt函数的源码。

function get_the_excerpt( $post = null ) {

if ( is_bool( $post ) ) {

_deprecated_argument( __FUNCTION__, '2.3.0' );

}

$post = get_post( $post );

if ( empty( $post ) ) {

return '';

}

if ( post_password_required( $post ) ) {

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

}

/**

* Filters the retrieved post excerpt.

*

* @since 1.2.0

* @since 4.5.0 Introduced the `$post` parameter.

*

* @param string $post_excerpt The post excerpt.

* @param WP_Post $post Post object.

*/

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

}

从上面代码中可以看出,get_the_excerpt函数直接取出了从数据库查到的文章数据。

参数

the_excerpt函数只能使用在WordPress主循环中,不需要参数。

get_the_excerpt函数参数是文章id,可以通过文章id获取到文章的摘要数据,可以不填,不填时与the_excerpt一样,不在文章主循环可能会出现错误,带参数可以在主循环外使用。

函数使用方法

注意,这个函数获取的文章摘要将会以[…]结尾,如代码狗博客的文章列表摘要,如果你不喜欢,可以使用字符串替换函数替换掉。

如果你对截取的字符数不满意,可以使用PHP字符串截取函数自行截取摘要字数,太简单了就不说了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值