admin管理员组

文章数量:1333187

I have a menu name Social Network. I want to get the menus ID. I tried the following, but didn't succeed.

  global $wpdb;
$menu_slug = 'social-network';
$menu_id = $wpdb->get_results(
    "
    SELECT TERM_ID
    FROM $wpdb->wp_terms
    WHERE name = ".$menu_slug."
    "
);
echo $menu_id;

I have a menu name Social Network. I want to get the menus ID. I tried the following, but didn't succeed.

  global $wpdb;
$menu_slug = 'social-network';
$menu_id = $wpdb->get_results(
    "
    SELECT TERM_ID
    FROM $wpdb->wp_terms
    WHERE name = ".$menu_slug."
    "
);
echo $menu_id;
Share Improve this question edited Jun 26, 2013 at 10:10 Bhuvnesh asked Jun 26, 2013 at 9:33 BhuvneshBhuvnesh 111 gold badge2 silver badges5 bronze badges 1
  • What exactly is inside $args? – kaiser Commented Jun 26, 2013 at 9:38
Add a comment  | 

4 Answers 4

Reset to default 8

You can use the function get_term_by and use 'name' in the field param.

<?php get_term_by( $field, $value, $taxonomy, $output, $filter ) ?> 

Example:

$term = get_term_by('name', 'Social Network', 'nav_menu');
$menu_id = $term->term_id;

Here is the link to the codex page: http://codex.wordpress/Function_Reference/get_term_by

Hope this helps.

All you need is get_terms()

Let's write wp_menu_id_by_name( $name )

/**
 * Gets a menu id by name
 * 
 * @param string $name The menu name
 * @return int|boolean The menu id or false if not found
 */
function wp_menu_id_by_name( $name ) {
    $menus = get_terms( 'nav_menu' ); 

    foreach ( $menus as $menu ) {
        if( $name === $menu->name ) {
            return $menu->term_id;
        }
    }
    return false;
}

Let's use it

echo 'My Special Menu id is ' . wp_menu_id_by_name( 'My Special menu' );

// Outputs: My Special Menu id is 3

I've used the wp_get_nav_menu_object. You can pass menu slug or name to it to get the menu object and then you can access the term_id from it. Codex for wp_get_nav_menu_object.

$menu_obj = wp_get_nav_menu_object(MENU_SLUG);
$menu_id  = $menu_obj ? $menu_obj->term_id : 0;

You don't use the right code, use this instead:

global $wpdb;

$tablename = $wpdb->prefix.'terms'; // use always table prefix
$menu_name = 'top-menu'; // menu name
$menu_id = $wpdb->get_results(
    "
    SELECT term_id
    FROM ".$tablename." 
    WHERE name= '".$menu_name."'
    "
);

// results in array 
foreach($menu_id as $menu):
    echo $menu->term_id;
endforeach; 

本文标签: get menu id using its name