PHP自定义短代码输出追加“Array”字样,如何解决?
解决WordPress自定义最后更新日期代码输出“Array”的问题
问题出在哪
- 钩子类型用错:你用
add_shortcode()注册the_content,但the_content是WordPress的内容过滤器钩子,不是短代码。错误的注册方式会导致WordPress处理内容时返回数组,最终被转成“Array”字符串输出。 - 变量未初始化:
$custom_content在使用.=拼接前没有定义初始值,默认是null,拼接操作会触发非预期的类型转换。
修复后的代码
// 显示文章最后更新日期 function show_last_updated( $content ) { // 初始化空字符串变量 $custom_content = ''; $u_time = get_the_time('U'); $u_modified_time = get_the_modified_time('U'); // 仅当修改时间比发布时间晚至少一天时显示更新日期 if ($u_modified_time >= $u_time + 86400) { $updated_date = get_the_modified_time('m/d/Y'); $custom_content .= '<p class="last-updated-date">Updated: '.$updated_date.'</p>'; } $custom_content .= $content; return $custom_content; } // 使用add_filter挂钩the_content过滤器,替代错误的add_shortcode add_filter( 'the_content', 'show_last_updated' );
核心修改说明
- 将
add_shortcode替换为add_filter,这是WordPress修改文章内容的正确钩子用法。 - 在函数开头给
$custom_content赋空字符串,避免未定义变量引发的字符串转换问题。
内容的提问来源于stack exchange,提问作者Tristen Arnold
相关产品推荐
相关产品推荐

