如何通过add_filter修改shortcode_atts的默认值?附代码示例
正确修改短码默认属性值的方法
你之前的问题出在用错了过滤器钩子,并且短码函数里存在一个输出逻辑错误,下面是修正方案:
核心问题说明
- 你要修改
shortcode_atts的默认值,应该用WordPress提供的专用钩子shortcode_atts_{$shortcode_tag},而不是自己定义的the_author_shortcode(这个钩子是用来修改最终HTML输出的)。 - 原短码里的
the_author()会直接输出作者名,而非返回值,导致sprintf的输出顺序混乱,必须换成get_the_author()。
修正后的完整代码
1. 修正短码函数
function author_of_posts($atts) { $defaults = [ 'after' => '', 'before' => '', ]; // 第三个参数"post_author"是短码标识,对应后续的过滤器钩子 $atts = shortcode_atts($defaults, $atts, 'post_author'); // 用get_the_author()获取返回值,而非the_author()直接输出 $output = sprintf('%1$s<span class="author">%2$s</span>%3$s', esc_html($atts['before']), esc_html(get_the_author()), esc_html($atts['after']) ); return apply_filters('the_author_shortcode', $output, $atts); } // 注册短码(如果之前没加的话) add_shortcode('post_author', 'author_of_posts');
2. 正确的默认值修改过滤器
// 钩子格式为shortcode_atts_{短码标识},这里对应"post_author" add_filter('shortcode_atts_post_author', 'change_post_author_shortcode_defaults', 10, 2); function change_post_author_shortcode_defaults($atts, $defaults) { // 仅当用户未设置before参数时,替换为自定义默认值 if (empty($atts['before'])) { $atts['before'] = 'Writer: '; } // 同理可以修改after的默认值 // if (empty($atts['after'])) { // $atts['after'] = '|'; // } return $atts; }
关键逻辑解释
shortcode_atts_{$shortcode_tag}是WordPress专门为修改短码属性默认值设计的钩子,其中$shortcode_tag就是你调用shortcode_atts时传入的第三个参数(这里是post_author)。- 过滤器函数必须声明接收2个参数:
$atts是合并后的属性数组,$defaults是原始默认值数组,通过10, 2指定优先级和参数数量。 - 使用
esc_html()对输出内容进行转义,避免XSS安全问题。
内容的提问来源于stack exchange,提问作者Samar Dev
相关产品推荐
相关产品推荐

