2

I have a menu:

Activities
Projects
About Us
News

(not counting submenu items).

Now "Activities" has no submenu.

I created custom content type "project".

My boss want to fill the menu "Activities" with the list of all projects automatically.

Can it be done without rewriting anew all WP menu output code?

1
  • What exactly do you mean by this?:"My boss want to fill the menu "Activities" with the list of all projects automatically." What are "projects"? Post types? Posts? Apr 11, 2012 at 13:59

2 Answers 2

1

Yes! Yes it can, you will need to hook into the filter used by the walker, e.g.:

add_filter( 'walker_nav_menu_start_el', 'menu_show_project_post', 10, 4 );

function menu_show_project_post( $item_output = '', $item = '', $depth = '', $args = '' ) {
    global $post;

    if ( is_array( $item->classes ) ) {
        $query = false;
        foreach( $item->classes as $class ) {
            if ( $class == 'project_posts') {
                $query = true;
                break;
            }
        }

        if ( $query ) {
            $the_posts = get_posts( array(
                'post_type' =>  'project',
                'numberposts' => 5
            ) );

            if ( ! empty( $the_posts ) ) {
                $new_html[] = '<ul class="sub-menu">';

                foreach( ( array ) $the_posts as $post ) {
                    setup_postdata( $post );
                    $new_html[] = '<li class="menu-item">';
                    $new_html[] = '<a href="' . get_permalink( ) . '" class="depth-' . ( $depth ? $depth + 1 : 2 ) . '">';
                    $new_html[] = the_title('','',false );
                    $new_html[] = '</a>';
                    $new_html[] = '</li>';
                }
                wp_reset_postdata();

                $new_html[] = '</ul>';

                $item_output .= implode( "\n", $new_html );
            }
        }
    }
    return $item_output;
}

With this code in functions.php, any menu item containing the class 'project_posts' will be given a submenu containing 5 posts of type project.

Modify the code as you wish to show however many posts or post types as you want

0

I think you might get around it with writing a custom menu walker that intercepts your Activities page and injects the project-type posts.

See http://codex.wordpress.org/Function_Reference/wp_nav_menu, the walker option.

For your custom walker you can easily extend Walker_Nav_Menu, located in wp-includes/nav-menu-template.php. The method start_el should be suitable for your needs.

That's how I'd do it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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