0

I want to add submenu to a navigation menu in wordPress through code (not through admin panel) and I am totally new to Wordpress. Any help would be greatly appreciated! Thanks!

0

Can you describe why you want to do it through code rather than the admin panel?

Your answer might be found in wp_nav_menu. Search around for how to display submenus… such as described here.

0

I think you get caught in providing the parent slug to the submenu function. Here is the example code and structure from codex for the function add_submenu_page which may help you understand to get your solution.

add_action( 'admin_menu', 'my_custom_menu' );

function my_custom_menu(){

    //add_menu_page( string $page_title, string $menu_title, string $capability, string $menu_slug, callable $function = '', string $icon_url = '', int $position = null )



    //add_submenu_page( string $parent_slug, string $page_title, string $menu_title, string $capability, string $menu_slug, callable $function = '' );

    add_submenu_page( 'custom-options', 'Edit Image', 'Edit Images', 'manage_categories', 'edit-images', function_to_handle_the_request );
}


function function_to_handle_the_request(){
   print '<div class="wrap">';

    $file = "/path-to-your-file"; //get_stylesheet_directory() may be helpful

    if ( file_exists( $file ) )
        require $file;

    print '</div>';
}
0

I got the answer, here it is: I want to add submenus ffrom database to the menu named 'Products'

Create a custom plugin and install it through Admin panel. Inside the functions.php write this code. This is upgrade safe way and will not brake if the theme is updated.

add_filter( 'wp_nav_menu_objects', 'ravs_add_menu_parent_class' );
 function ravs_add_menu_parent_class( $items ) {
  $results = 'SOME SQL QUERY';
  foreach ( $items as $item ) {
    $title = $item->title;
    $ID = $item->ID;
    if($title=='Products')
        $parentId = $ID;
  }
  foreach ( $results as $result ) {
  $name = $result->name;
  $id = $result->id;
  $link = array (
        'title'            => $name,
        'menu_item_parent' => $parentId,
        'ID'               => $id,
        'db_id'            => $id,
        'url'              => 'URL'
    );

  $items[] = (object) $link;
  }
  return $items;   
}

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.