我已经在我的WordPress functions.php文件中创建了一个函数,当您在/查看自定义post类型的页面时,它会突出显示一些链接。
我是一个php的新手,所以我想问一个人,我怎样才能改变这段代码,使其减少重复/冗余?
正如你在下面看到的,我有两个相同的post类型,并且class语句被设置了四次。链接也位于两个不同的菜单位置,因此是双重的。
// filter current_page_parent to events menu link
function menu_class_filter_event($classes) {
// Remove "current_page_parent" class
$classes = array_diff($classes, array('current_page_parent'));
// If this is the "event" custom post type, highlight the correct menu items
if (in_array('menu-item-36', $classes) && get_post_type() === 'event') {
$classes[] = 'current_page_parent';
}
if (in_array('menu-item-54', $classes) && get_post_type() === 'event') {
$classes[] = 'current_page_parent';
}
// If this is the "program" custom post type, highlight the correct menu items
if (in_array('menu-item-124', $classes) && get_post_type() === 'program') {
$classes[] = 'current_page_parent';
}
if (in_array('menu-item-126', $classes) && get_post_type() === 'program') {
$classes[] = 'current_page_parent';
}
return $classes;
}
add_filter('nav_menu_css_class', 'menu_class_filter_event', 10, 2);发布于 2021-07-17 18:42:56
我的PHP不是很流利,但我可能会尝试将其全部转移到一个if下。
// filter current_page_parent to events menu link
function menu_class_filter_event($classes) {
// Remove "current_page_parent" class
$classes = array_diff($classes, array('current_page_parent'));
$add_class =
get_post_type() === 'event' && (
in_array('menu-item-36', $classes) ||
in_array('menu-item-54', $classes))
|| get_post_type() === 'program' && (
in_array('menu-item-124', $classes) ||
in_array('menu-item-126', $classes));
if ($add_class) {
$classes[] = 'current_page_parent';
}
return $classes;
}您可以尝试像here那样组合in_array,但我不认为在这种情况下会增加可读性。
https://stackoverflow.com/questions/68419647
复制相似问题