0

Is it possible to check in WP if the current page/menu item is a child or a parent with child (in my wp_nav_menu)? So not if the page has a child page, but if the menu item is a parent with child or a child (based on my wp_nav_menu).

  • It is a bit unclear what you are trying to achieve. You should specify you question and add relevant information. – Nicolai Jan 16 '15 at 14:34
  • Well, when Im on a page, i want to check whether the page is a child or a parent (with a child), based on the defined wp_nav_menu in WP admin. Hope that is clear. – RobbertT Jan 16 '15 at 14:36
  • 1
    You know about the nav menu css classes? Otherwise you likely have to deal with Walker_Nav_Menu in one or another way. – Nicolai Jan 16 '15 at 14:36
1

I agree with ialocin, if you can use the built-in nav menu css classes you should but if those aren't enough there's a nice little filter which can help with css classes. If you need something other than CSS classes you can use a Custom Walker ( as ialocin suggested ) and use the same logic as the function below.

Add some CSS Classes to WP Nav Menu

/** Custom `wp_nav_menu()` Classes **/
function add_class_to_wp_nav_menu( $classes, $item ) {

    if( hasChildren( $item->object_id ) ) {                     // hasChildren is a Custom Function
        array_push( $classes, 'has-children' );
    }

    if( 0 !== wp_get_post_parent_id( $item->object_id ) ) {     // 0 means there is no parent
        array_push( $classes, 'has-parent' );
    }

    return $classes;
}
add_filter( 'nav_menu_css_class', 'add_class_to_wp_nav_menu', 10, 2 );

/** Check if Page has Children **/
function has_children( $pid ) {
    $children = get_pages( "child_of={$pid}" );
    return ( $children );
}
  • 1
    Correct answer, I guess - but isn't this just duplicating existing classes, e.g. menu-item-has-children or current-menu-parent? So you could just use them. @RobbertT – Nicolai Jan 16 '15 at 15:00
  • @ialocin ha, yeah I guess you're right. Default classes are pretty informative. – Howdy_McGee Jan 16 '15 at 15:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.