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

在做企业主题开发的时候,一般都会有几种文章类型,对于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');

就是这样!

来源:

https://www.wpdaxue.com/wordpress-different-post-types-excerpt-length.html

微信公众号
手机浏览(小程序)

Warning: get_headers(): SSL operation failed with code 1. OpenSSL Error messages: error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(): Failed to enable crypto in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57

Warning: get_headers(https://static.shanhubei.com/qrcode/qrcode_viewid_32111.jpg): failed to open stream: operation failed in /mydata/web/wwwshanhubei/web/wp-content/themes/shanhuke/single.php on line 57
0
分享到:
没有账号? 忘记密码?