调整博客首页摘要格式

Auth:老郭       Date:2025/03/07       Cat:网络       Word:共 314 个字符/单词       Views:16

前两天,老郭通过修改代码调整博客正文字体大小,效果还是蛮满意的。而在此之前,老郭已经修改博客首页文章摘要字数,但是,首页文章摘要格式还是存在一些需要调整的地方。

这个主题首页文章摘要不支持段落格式,所有的文字全部连在一起,看上去不太美观。通过咨询AI,是因为 the_​excerpt() 默认会移除所有 HTML 标签(包括),导致段落结构丢失。AI给出的解决办法是在functions.php文件的末尾添加自定义摘要函数。

function custom_​excerpt_​with_​paragraphs_​filter( $excerpt ) {
    global $post;
    $content = get_​the_​content();
    $content = strip_​shortcodes( $content );
    $content = apply_​filters( 'the_​content', $content ); // 保留格式
    $content = str_​replace( ']]>', ']]>', $content );

    // 处理段落分割(兼容单换行和双换行)
    $paragraphs = preg_​split( "/\n{1,}/", $content ); // 使用正则分割,支持单或多换行
    $excerpt = '';
    $char_​count = 0;
    $max_​chars = 260; // 与你的设置一致

    foreach ( $paragraphs as $paragraph ) {
        if ( empty( trim( $paragraph ) ) ) continue;
        $paragraph_​clean = strip_​tags( $paragraph, '<p>' ); // 保留 <p> 标签
        $chars = mb_​strlen( strip_​tags( $paragraph_​clean ), 'UTF-8' );
        if ( $char_​count + $chars <= $max_​chars ) {
            $excerpt .= '<p>' . trim( $paragraph_​clean ) . '</p>';
            $char_​count += $chars;
        } else {
            $remaining_​chars = $max_​chars - $char_​count;
            if ( $remaining_​chars > 0 ) {
                $excerpt .= '<p>' . mb_​substr( strip_​tags( $paragraph ), 0, $remaining_​chars, 'UTF-8' ) . '...</p>';
            }
            break;
        }
    }

    return $excerpt;
}
add_​filter( 'the_​excerpt', 'custom_​excerpt_​with_​paragraphs_​filter', 1000 ); // 高优先级确保覆盖其他过滤器

这样,首页摘要就能正确的显示段落了。不过,段落有了,其他的格式问题又冒了出来,一是摘要同样没有首行缩进,二是摘要段落之间间距有些大。那就继续修改,在style.css文件里找到以下代码:

.entry-content,
.entry-summary,
.mu_​register {
    line-height: 2.4;
    margin: 0 0 1.714285714rem;
    line-height: 1.714285714;

然后在其后添加:

/* 调整摘要段落间距,添加 !important 或更高优先级 */
.entry-content p,
.entry-summary p,
.mu_​register p {
    margin: 0 0 24px;
    margin: 0 0 1.714285714rem;
    line-height: 1.714285714;
}
.entry-summary p {
    margin-bottom: 12px !important; /* 使用 !important 强制覆盖 */
    margin-bottom: 0.857142857rem !important;
    text-indent: 2em;
}

如此,首页摘要的首行缩进和行间距问题也解决了,博客的首页看上去好看多了。

⚑Tags:      

老郭博客文章均为原创,本文地址 https://lgbk.cn/archives/2607.html,转载请以链接形式注明出处。

作者:

《调整博客首页摘要格式》留言数:0

发表留言