5ucms论坛

标题: the_excerpt()函数 获取文章摘要 get_the_excerpt() [打印本页]

作者: admin    时间: 2021-5-31 14:38
标题: the_excerpt()函数 获取文章摘要 get_the_excerpt()
wordpress内置函数 the_excerpt() 是个使用频率较高的函数,它是用来获取当前文章摘要的,以[…]结尾,如果在文章中没有编辑内容摘要字段,则默认截取文章的前55个字的内容,默认截取的字段去掉HTML标签和图形,并且一定要在循环内使用。

the_excerpt() 函数使用的方法也非常简单,用法如下:

这个标签没有任何的参数,直接使用即可,但函数默认的设置有时候并不能满足用户的需要,比如国内用户以[…]结尾就很不习惯,另外截取前 55 个字符有时候会太少了,还有文章摘要的结尾是不是我们可以自定义加个更多的链接呢,这些自定义只需要在主题 functions.php 文件中加入相应的代码就可以了。

functions.php中的代码

  1. //设定摘要的长度
  2. function new_excerpt_length($length) {
  3.     return 150;
  4. }
  5. add_filter('excerpt_length', 'new_excerpt_length');

  6. //把摘要默认的结尾[...]换成...
  7. function new_excerpt_more(){
  8.     global $post;
  9.     return " <a href="". get_permalink($post->ID) . "">阅读更多</a>";
  10. }
  11. add_filter('excerpt_more', 'new_excerpt_more');
复制代码

//在页面中直接调用摘要
  1. <?php the_excerpt();?>

  2. //也可以采用这种方法,但是测试的结果却是摘要字符无法截断,如果能截断这个是比较完美的一个方法
  3. <?php if(has_excerpt()){
  4.     the_excerpt();
  5. } else{
  6.     echo mb_strimwidth(strip_tags(apply_filters('the_content', $post->post_content)), 0, 75, "…");
  7. }?>
复制代码

get_the_excerpt() 返回文章摘要赋值给变量




欢迎光临 5ucms论坛 (http://bbs.5ucms.com/) Powered by Discuz! X3.2