如何在WordPress的oEmbed链接中移除author_name与author_url字段
解决方案:保留oEmbed链接并移除指定字段
当然有办法实现你的需求!WordPress提供了专门的过滤器来修改oEmbed的响应数据,这样你既能保留页面头部的oEmbed链接标签,又能移除author_name和author_url这两个字段。具体操作如下:
1. 使用oembed_response_data过滤器
这个过滤器允许你直接修改oEmbed返回的JSON数据结构。你只需要在主题的functions.php文件或者自定义插件中添加以下代码:
add_filter('oembed_response_data', 'remove_oembed_author_fields', 10, 4); function remove_oembed_author_fields($data, $post, $width, $height) { // 检查并移除author_name字段 if (isset($data['author_name'])) { unset($data['author_name']); } // 检查并移除author_url字段 if (isset($data['author_url'])) { unset($data['author_url']); } // 返回修改后的数据集 return $data; }
2. 代码说明
- 我们通过
add_filter注册了一个名为remove_oembed_author_fields的回调函数,绑定到oembed_response_data过滤器上。 - 回调函数接收四个参数:
$data是原始的oEmbed响应数据数组,$post是当前的文章/页面对象,$width和$height是oEmbed内容的尺寸参数。 - 我们通过
isset()检查目标字段是否存在,避免直接unset不存在的字段引发警告,然后用unset()移除这两个字段。 - 最后返回修改后的
$data数组,WordPress会自动用这个新数组生成对应的oEmbed响应(包括页面头部的链接指向的JSON/XML数据)。
3. 可选:针对特定内容类型调整
如果你只想在特定类型的内容(比如文章、自定义文章类型)中移除这些字段,可以在函数中添加条件判断,比如:
add_filter('oembed_response_data', 'remove_oembed_author_fields', 10, 4); function remove_oembed_author_fields($data, $post, $width, $height) { // 仅针对文章类型移除字段 if (get_post_type($post) === 'post') { if (isset($data['author_name'])) { unset($data['author_name']); } if (isset($data['author_url'])) { unset($data['author_url']); } } return $data; }
注意事项
- 建议在修改
functions.php之前备份文件,避免代码错误导致网站异常。 - 如果使用子主题,优先将代码添加到子主题的
functions.php中,这样主题更新时不会丢失修改。
内容的提问来源于stack exchange,提问作者user4419473
相关产品推荐
相关产品推荐

