摄影大咖 发表于 2019-10-28 12:35:24

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');就是这样!是不是特别简单
页: [1]
查看完整版本: WordPress 不同文章类型设置不同摘要长度的方法