让我们先看看这一部分:
我不太明白什么东西$item
这可能就是问题所在。当我打电话时get_class()
在…上$item
我明白了WP_Post
, 但是WP_Post
没有classes属性。那么$item->classes
返回类数组?
关于WordPress中菜单结构的几点注意事项:
每个导航菜单在nav_menu
分类学
然后,当我们向该菜单添加项目时,我们正在创建该类型的新post对象nav_menu_item
.
每个菜单的树结构不是存储在post_parent
的字段nav_menu_item
职位,如预期。我们实际上在post meta表中找到了它,它存储在_menu_item_menu_item_parent
元键,针对每个nav_menu_item
邮递
在$item
菜单项数据对象是修饰的WP_Post
对象,即使用wp_setup_nav_menu_item()
功能:
/**
* Decorates a menu item object with the shared navigation menu item properties.
*
* Properties:
* - ID: The term_id if the menu item represents a taxonomy term.
* - attr_title: The title attribute of the link element for this menu item.
* - classes: The array of class attribute values for the link element of this menu item.
* - db_id: The DB ID of this item as a nav_menu_item object, if it exists (0 if it doesn\'t exist).
* - description: The description of this menu item.
* - menu_item_parent: The DB ID of the nav_menu_item that is this item\'s menu parent, if any. 0 otherwise.
* - object: The type of object originally represented, such as "category," "post", or "attachment."
* - object_id: The DB ID of the original object this menu item represents, e.g. ID for posts and term_id for categories.
* - post_parent: The DB ID of the original object\'s parent object, if any (0 otherwise).
* - post_title: A "no title" label if menu item represents a post that lacks a title.
* - target: The target attribute of the link element for this menu item.
* - title: The title of this menu item.
* - type: The family of objects originally represented, such as "post_type" or "taxonomy."
* - type_label: The singular label used to describe this type of menu item.
* - url: The URL to which this menu item points.
* - xfn: The XFN relationship expressed in the link of this menu item.
* - _invalid: Whether the menu item represents an object that no longer exists.
然后让我们看看这一部分:
使用类后search-class
要查找该项目,我想将其从该项目中删除。然而,我的电话unset($item->classes[$class_key]);
不起作用。
从中删除类为时已晚$item
对象,在nav_menu_link_attributes
筛选,以便从菜单项(li标记)中删除类。
例如,我们可以使用nav_menu_css_class
筛选以修改这些类。
一般来说,使用这样的过滤器而不是直接修改数据对象可能是更好的方法,因为其他插件可能依赖于原始数据对象
下面是一个如何删除search-class
类别:
add_filter( \'nav_menu_css_class\', function( $classes, $item, $args, $depth )
{
return array_filter(
(array) $classes,
function( $val ) { return \'search-class\' !== $val; }
);
}, 10, 4 );
然后我们可以使用
nav_menu_link_attributes
筛选以添加数据属性并将类附加到定位标记:
add_filter( \'nav_menu_link_attributes\', function( $atts, $item, $args )
{
// Nothing to do
if(
! isset( $item->classes )
|| ! in_array( \'klasi1\', $item->classes, true )
|| ! isset( $atts[\'class\'] )
)
return $atts;
// Add data attribute to anchor tag
$atts[\'data-something\'] = \'something\';
// Append an anchor class
$classes = explode( \' \', $atts[\'class\'] );
$classes[] = \'something-class\';
$atts[\'class\'] = join( \' \', array_filter( $classes ) );
return $atts;
}, 10, 3 );
我们还可以通过检查
$args->theme_location
是
\'primary\'
或
$args->menu->slug
是
\'somemenuslug\'
.