首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >我如何压缩我的重复/冗余的php代码?

我如何压缩我的重复/冗余的php代码?
EN

Stack Overflow用户
提问于 2021-07-17 18:29:05
回答 1查看 29关注 0票数 0

我已经在我的WordPress functions.php文件中创建了一个函数,当您在/查看自定义post类型的页面时,它会突出显示一些链接。

我是一个php的新手,所以我想问一个人,我怎样才能改变这段代码,使其减少重复/冗余?

正如你在下面看到的,我有两个相同的post类型,并且class语句被设置了四次。链接也位于两个不同的菜单位置,因此是双重的。

代码语言:javascript
复制
// 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);
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-07-17 18:42:56

我的PHP不是很流利,但我可能会尝试将其全部转移到一个if下。

代码语言:javascript
复制
// 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,但我不认为在这种情况下会增加可读性。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68419647

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档