Borgtex Borgtex - 5 months ago 9
PHP Question

Force ancestor page for another page in wordpress

My customer has a Wodpress blog with a page named "Galleries" that serves as a kind of main page as he manually writes there links to other pages, both local and external.

The main menu for the blog has also a link to this Galleries page. Problem is that the menu item only is active for that page, but not for the linked local pages, unless you previously selected Galleries as their parent page.

So I was wondering if it will be possible (with a hook) to virtually force an ancestor to a page that meets certain conditions before the menu is rendered, avoiding the need to manually edit every page and make it a child to "Galleries"

Answer

Finally found how to do it:

$main_gallery_page= get_page_by_title('Galleries');

add_filter('nav_menu_css_class' , 'force_ancestor_nav_class' , 10 , 2);

function force_ancestor_nav_class($classes, $item){
    global $main_gallery_page,$post;

    //condition: could be any condition: by category, title, contents, ...
    $make_ancestor=substr( $post->post_title, 0, 7 ) === "Gallery";

    //only adds the class if the condition is met and not already present
    if ($item->object_id==$main_gallery_page->ID && $make_ancestor && !in_array('current-page-ancestor',$classes)) {$classes[]='current-page-ancestor';}

    return $classes;
}
Comments