• Hi everyone,

    I’m looking for the code to:

    1. check if a menu with name ‘main-menu’ exists. If not, create it.
    2. assign it the menu location primary
    3. add a ‘home’ link to the menu

    So I’m looking for something like this but this code isn’t working:

    if ( !has_nav_menu( 'main-menu' ) ) {
      register_nav_menu('main-menu',__( 'Main menu' ));
      //somehow add a link to the homepage to main-menu
      add_action( 'init', 'main-menu' );
    }

    Already thanks for all the help.

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    I don’t have specific code, but I can summarize how menus are organized in the DB so you can decide how to manipulate the data to achieve what you want.

    Every menu item is a post of type “nav_menu_item”. The item’s link type and URL and other data are in postmeta. Each item is assigned to a menu through the “nav_menu” taxonomy. The assigned taxonomy term is the menu name. Menus are associated to theme locations through theme mod “nav_menu_locations”. Each location is associated with a term ID here.

    1) search terms table for the name “main-menu”. Ensure the term ID relates to the right taxonomy in term_taxonomy table. Insert appropriate records if needed.

    2) Alter theme’s theme_mod accordingly if needed.

    3) Insert appropriate post and post meta and assign desired taxonomy term. Use existing items as a guide for proper field values.

    Thread Starter twentyfourdegrees

    (@twentyfourdegrees)

    Oh that’s a nice approach: injecting it in the database directly. I will investigate, thank you very much.

    Moderator bcworkz

    (@bcworkz)

    You’re welcome. There may be WP PHP functions that do some or all of it so you don’t necessarily need to interact directly all the time. Direct interaction can be risky if not done correctly. WP PHP functions are generally safer. Making direct SELECT queries is pretty safe, but directly writing data is where the danger lies. I recommend using appropriate WP PHP functions to write data, like wp_insert_post() and wp_set_object_terms() for example, or better yet, wp_update_nav_menu_item().

    All the same, you still should understand how nav menu data is organized in order to properly use WP PHP functions. TBH, I’m not aware of all possible nav menu functions. In the code reference search field type in “nav_menu” and you’ll get a long list of suggestions of possible nav menu related functions.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Create a custom meu with location and a home page’ is closed to new replies.