前两天,老郭通过修改代码调整博客正文字体大小,效果还是蛮满意的。而在此之前,老郭已经修改博客首页文章摘要字数,但是,首页文章摘要格式还是存在一些需要调整的地方。
这个主题首页文章摘要不支持段落格式,所有的文字全部连在一起,看上去不太美观。通过咨询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; }
如此,首页摘要的首行缩进和行间距问题也解决了,博客的首页看上去好看多了。
本文首发于:调整博客首页摘要格式-老郭博客
《调整博客首页摘要格式》留言数:0