MySQLPHPWordPress

Fetch menu id by menu name of WordPress

0
631
2017 / 11 / 24

WordPress usually stores menu ID in its “terms” table. If you know your table prefix than you can use the prefix along with the “terms” and if you don’t know the prefix than not to worry at all you can use $wpdb->prefix to get the table prefix.

Today I am going to write SQL query that will help you to get the menu ID from the database of WordPress website.

Explanation

First of all, we will write menu name. In my example I have used “My Menu”:

$menu_name = 'My Menu';

Note that you should write exact name, “My Menu” is different from “My menu” and “my menu”.

Now we will be creating the table along with the prefix:

$tablename = $wpdb->prefix.'terms';

The $tablename variable now have the table name along with prefix and it will be used to create SQL query.

$menu_id = $wpdb->get_results(
    "
    SELECT term_id
    FROM ".$tablename." 
    WHERE name= '".$menu_name."'
    "
);

The $menu_id will get the data received by the execution of SQL query.

Now we will be fetching menu ID from it as:

foreach($menu_id as $menu):
    echo $menu->term_id;
endforeach;

The $menu->term_id will return the menu ID, now you can use that menu ID to fetch further details and objects for particular menu.

 

The Full Code

global $wpdb;
$menu_name = 'My Menu';
$tablename = $wpdb->prefix.'terms';
$menu_id = $wpdb->get_results(
    "
    SELECT term_id
    FROM ".$tablename." 
    WHERE name= '".$menu_name."'
    "
);
foreach($menu_id as $menu):
    echo $menu->term_id;
endforeach;

Hi, I am a full-stack web developer with 5+ years of experience in working with different web technologies. Do you want to ask something? just send me a message through the contact form. Please visit my portfolio at hamzamehmood.com. Thanks