欢迎您光临自学哈网,只为分享网络知识教程,供大家学习参考!

「自学哈网」WordPress 不同文章类型设置不同摘要长度

作者 : 自学哈 本文共903个字,预计阅读时间需要3分钟 2022-11-26 共117人阅读
也想出现在这里? 联系我们

在做企业主题开发的时候,一般都会有几种文章类型,对于WordPress而言,设置摘要长度比较规范的用法是通过钩子 excerpt_length 去实现。

设置摘要长度

比如常用代码范例如下:

/**
 * 通过钩子设置摘要长度为 30
 *
 * @param int $length Excerpt length.
 * @return int (Maybe) modified excerpt length.
 */
function wpdaxue_excerpt_length( $length ) {
    return 30;
}
add_filter( \'excerpt_length\', \'wpdaxue_excerpt_length\');

设置摘要的更多字符

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

/**
 * 钩子设置摘要后的更多字符
 */
 function wpdaxue_excerpt_more( $more ) {
     return \'...\';
 }
 add_filter( \'excerpt_more\', \'wpdaxue_excerpt_more\' );

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

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

/**
 * 不同文章类型设置不同摘要长度
 */
function wpdaxue_variable_excerpt_length( $length ) {
  // 使用全局变量 $post 检测当前文章所属的文章类型
  global $post;
  
  // 针对不同的文章类型设置不同长度
  if ( \'post\' === $post->post_type ) {
    return 32;
  } else if ( \'page\' === $post->post_type ) {
    return 65;
  } else if ( \'products\' === $post->post_type ) {
    return 75;
  } else {
    return 80;
  }
}
add_filter( \'excerpt_length\', \'wpdaxue_variable_excerpt_length\');

就是这样!

本站声明:
本站所有资源来源于网络,分享目的仅供大家学习和交流!如若本站内容侵犯了原著者的合法权益,可联系邮箱976157886@qq.com进行删除。
自学哈专注于免费提供最新的分享知识、网络教程、网络技术的资源分享平台,好资源不私藏,大家一起分享!

自学哈网 » 「自学哈网」WordPress 不同文章类型设置不同摘要长度
也想出现在这里? 联系我们
© 2022 Theme by - 自学哈网 & WordPress Theme. All rights reserved 浙ICP备2022016594号