WordPress教程

WordPress 实现不同文章类型设置不同摘要长度

阿里云

在做企业主题开发的时候,一般都会有几种文章类型,对于 WordPress 而言,设置文章摘要长度比较规范的用法是通过钩子 excerpt_length 去实现,那么 he_exceprt 和 the_content 之间的差异是什么呢?大多数 WordPress 主题使用 The Loop 内部的 the_content()来显示预览内容,然后使用 Read More 样式链接到本文的其余部分。使用 the_content 时 ,将输出<--more-->标记之前出现的文章中的所有内容,然后输出指向文章其余部分的链接。如果没有更多标签,则输出整篇文章。

当负责输出文章 WordPress 模板使用 the_excerpt 时 ,流程略有不同。 此标记 - the_excerpt - 必须在 The Loop 中使用。如果文章或自定义文章类型有手动摘要 ,那么将输出, 然后在方括号内输出省略号 。如果文章没有手动摘要,则文章前 55 个单词将用作摘要内容。 这个默认长度为 55 个单词是我们想要改变的,有几种方法可以做到这一点。

也想出现在这里?联系我们
创客主机

设置摘要

比如常用代码范例如下:

  1.     /**
  2.      * 通过钩子设置摘要长度为 30
  3.      *
  4.      * @param int $length Excerpt length.
  5.      * @return int (Maybe) modified excerpt length.
  6.      */
  7.     function jszbug_excerpt_length( $length ) {
  8.         return 30;
  9.     }
  10.     add_filter( 'excerpt_length', 'liwei8090_excerpt_length');

更多字符

通常,我们还需要借助 excerpt_more 钩子去自定义摘要后面的字符,默认为 […] ,如果要改为 … ,可以使用下面的代码范例:

  1.     /**
  2.      * 钩子设置摘要后的更多字符
  3.      */
  4.      function jszbug_excerpt_more( $more ) {
  5.          return '...';
  6.      }
  7.      add_filter( 'excerpt_more', 'liwei8090_excerpt_more' );

另一种获取自定义摘录长度的方法是使用 WordPress Codex 上提供的自定义摘要长度功能 。 此代码段直接进入您的 functions.php 文件。如果您在文章或自定义文章类型上启用了手动摘要,并且通过模板中的 the_excerpt()调用这些 the_excerpt() , 那些将覆盖此功能并显示您在其中输入的内容。下面的这种情况下,我们将显示文章内容的前十个单词。除非您在主题中添加了自定义“阅读更多”链接功能 ,否则将会显示[...] 。

  1.     /**
  2.      * 通过钩子设置摘要长度为 10
  3.      *
  4.      * @param int $length Excerpt length.
  5.      * @return int (Maybe) modified excerpt length.
  6.      */
  7.     function jszbug_excerpt_length( $length ) {
  8.         return 10;
  9.     }
  10.     add_filter( 'excerpt_length', 'liwei8090_excerpt_length');

不同文章类型设置不同摘要长度

言归正传,要为不同的文章类型设置不同的摘要长度,可以通过判断文章类型来分别定义,代码范例如下:

  1.     /**
  2.      * 不同文章类型设置不同摘要长度
  3.      */
  4.     function liwei8090_variable_excerpt_length( $length ) {
  5.       // 使用全局变量 $post 检测当前文章所属的文章类型
  6.       global $post;
  7.       // 针对不同的文章类型设置不同长度
  8.       if ( 'post' === $post->post_type ) {
  9.         return 32;
  10.       } else if ( 'page' === $post->post_type ) {
  11.         return 65;
  12.       } else if ( 'products' === $post->post_type ) {
  13.         return 75;
  14.       } else {
  15.         return 80;
  16.       }
  17.     }
  18.     add_filter( 'excerpt_length', 'liwei8090_variable_excerpt_length');

WordPress 实现不同文章类型设置不同摘要长度

已有 373 人购买
查看演示升级 VIP立刻购买

收藏
(0)

发表回复

热销模板

Ashade - 作品展示摄影相册WordPress汉化主题
LensNews

本站承接 WordPress / PbootCMS / DedeCMS 等
系统建站、仿站、开发、定制等业务!