Blog

  • Custom Post Type Posts in Menu Dynamically

    Posted at 20 Aug, 2018 in Tutorials

    You may want to add your Custom Post Type posts dynamically in the menu as dropdown and here is the solution.

    Step 1:

    Paste the following code in your theme’s ‘functions.php’. This will utilize the WordPress menu Walker class – end_el function.


    /** function to display custom post type post’s of first level **/
    class Walker_Dynamic_Submenu extends Walker_Nav_Menu {
    function end_el(&$output, $item, $depth=0, $args=array()) {
    if( 100 == $item->ID ){
    global $post;
    $cptnames = get_posts(array('post_type'=>'cptname','posts_per_page'=>-1, 'post_parent' => 0));
    if(!empty($cptnames)) {
    $output .= '<ul class="sub-menu">';
    foreach($cptnames as $post): setup_postdata($post);
    $output .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a>';
    $output .= get_child_posts(get_the_ID());
    $output .= '</li>';
    endforeach; wp_reset_postdata();
    $output .= '</ul>';
    }
    }
    $output .= "</li>\n";
    }
    }

    Replace cptname with your Custom Post Type name above.

    Step 2:

    Again paste the following code in your theme’s ‘functions.php’ if you have parent-child hierarchy for your Custom Post Type to display the children. You can skip this step if you don’t have hierarchy.


    /** function to display custom post type children posts **/
    function get_child_posts($parent = 0) {
    global $post;
    $cptnameschild = get_posts(array('post_type'=>'cptname','posts_per_page'=>-1, 'post_parent' => $parent));
    if(!empty($cptnameschild)) {
    $outputchild .= '<ul class="sub-menu">';
    foreach($cptnameschild as $post): setup_postdata($post);
    $outputchild .= '<li><a href="'.get_permalink().'">'.get_the_title().'</a></li>';
    $outputchild .= get_child_posts(get_the_ID());
    endforeach; wp_reset_postdata();
    $outputchild .= '</ul>';
    }
    return $outputchild;
    }

    Again, replace cptname with your Custom Post Type name above.

    Step 3:

    Now we are in the final part – we need to append our Walker function to the WordPress menu items. Add this , 'walker' => new Walker_Dynamic_Submenu to wp_nav_menu() – for example, wp_nav_menu( array( 'theme_location' => 'top', 'menu_id' => 'top-menu', 'walker' => new Walker_Dynamic_Submenu ) ).

Categories

Categories

Archives

Archives