WordPress自动生成文章署名异常:仅显示By无作者信息及链接
问题分析与解决
核心问题
- 变量作用域错误:你在函数外部定义的
$display_name和$user_website无法在函数内部访问,导致输出空值,所以只显示"By"。 - 生效范围受限:
is_single()仅让署名在单篇文章页面生效,首页文章摘要使用的是the_excerpt过滤器,未被处理。 - 未处理空网址情况:如果作者未填写个人网站,会生成无效空链接。
修正后的代码
将以下代码替换你原有的代码:
/* * Add byline to post content and excerpt */ if ( ! function_exists( 'wpfactory_add_author_byline' ) ) { function wpfactory_add_author_byline( $content ) { // Skip for admin or empty content if ( is_admin() || empty( $content ) ) { return $content; } // Get current post's author ID $author_id = get_post_field( 'post_author', get_the_ID() ); // Get author's display name $display_name = get_the_author_meta( 'display_name', $author_id ); // Get author's website URL $user_website = get_the_author_meta( 'url', $author_id ); // Build byline if ( ! empty( $user_website ) ) { $byline = 'By <a href="' . esc_url( $user_website ) . '">' . esc_html( $display_name ) . '</a>'; } else { $byline = 'By ' . esc_html( $display_name ); } // Add byline before content/excerpt, wrap in a container for styling (optional) $byline = '<div class="post-byline">' . $byline . '</div>'; return $byline . $content; } } // Apply to both single post content and home page excerpts add_filter( 'the_content', 'wpfactory_add_author_byline' ); add_filter( 'the_excerpt', 'wpfactory_add_author_byline' );
关键改进点
- 变量作用域修复:在函数内部获取当前文章的作者ID,确保每次调用都能拿到正确的作者信息。
- 覆盖所有场景:同时挂钩
the_content和the_excerpt,让单篇文章和首页摘要都显示署名。 - 安全处理:使用
esc_url()和esc_html()过滤输出内容,避免XSS安全问题。 - 空网址兼容:如果作者没有填写个人网站,直接显示作者名,不生成无效链接。
- 跳过后台:添加
is_admin()判断,避免在后台编辑页面显示署名。
内容的提问来源于stack exchange,提问作者Luke Kelly
相关产品推荐
相关产品推荐

