Search code examples
phpwordpresscustom-post-typeposts

how can I condense my repetitive/redundant php code?


I have created a function in my WordPress functions.php file to highlight a number of links when you are on/viewing custom post type pages.

I am a newbie with php, so I wanted to ask someone how can I change this piece of code to be less repetitive/redundant?

As you can see below, I have doubles of the same post types and the class statement is being set four times. The links are also positioned in two different menu locations, hence the doubling up.

// 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);

Solution

  • I'm not very fluent in PHP, but I would probably try to move it all under one 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;
    }
    

    You could try to combine the in_array like they did here, but I don't think it adds to readability in this case.