You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过function.php为HTML标签添加itemscope及itemtype属性

如何通过functions.php为HTML标签添加itemscope及带itemtype的itemscope属性

场景1:为标签添加itemscope itemtype="http://schema.org/WebPage"

要修改页面根节点的属性,利用WordPress的language_attributes过滤器即可实现,代码如下:

add_filter( 'language_attributes', 'add_html_schema_attributes' );
function add_html_schema_attributes( $output ) {
    $output .= ' itemscope itemtype="http://schema.org/WebPage"';
    return $output;
}

这段代码会在生成标签的属性时,自动追加schema相关属性,最终渲染出的标签会是类似<html lang="zh-CN" itemscope itemtype="http://schema.org/WebPage">的格式。

场景2:为特定元素(比如导航菜单链接)添加itemscope属性

如果是给导航菜单的标签添加属性,需要用nav_menu_link_attributes过滤器,修正你提供的参考代码后如下:

add_filter( 'nav_menu_link_attributes', 'add_menu_itemscope_attributes', 10, 3 );
function add_menu_itemscope_attributes( $atts, $item, $args ) {
    // 添加单独的itemscope属性
    $atts['itemscope'] = '';
    
    // 若需要同时指定itemtype,取消下面注释即可
    // $atts['itemtype'] = 'http://schema.org/WebPage';
    
    return $atts;
}

这个过滤器专门用于修改导航菜单链接的属性,直接往$atts数组中添加对应键值对,WordPress会自动处理成标准的HTML属性格式。

注意事项

  • 代码要添加到当前主题(或子主题)的functions.php文件末尾,用子主题修改可避免主题更新导致代码丢失
  • 单独的itemscope属性不需要赋值,设置为空字符串即可在HTML中渲染为<元素 itemscope>的格式

内容的提问来源于stack exchange,提问作者RSP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 02:13:15