如何通过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
相关产品推荐
相关产品推荐

