entity-command icon indicating copy to clipboard operation
entity-command copied to clipboard

WP CLI - Menu Item Get Command

Open NenadObradovic opened this issue 7 years ago • 3 comments

Hi guys,

Could you consider to improve wp menu item commands with get method?

I have the problem to get some information of existing menu items for example ID. I try dynamically to add new items as child elements but I can't get parent menu item ID. At this moment we have options to list all menu items and here I can see menu item ID

wp menu item list main-menu

but if I want to create a simple program to collect menu items information and to add new items in predefined places, then I can't do that. Thanks for your time

Best regards, Nenad

NenadObradovic avatar Nov 28 '18 14:11 NenadObradovic

@NenadObradovic If you want to retrieve the parent menu item ID, you can do this by adding the field menu_item_parent to the displayed fields:

wp menu item list main-menu --fields=db_id,title,menu_parent_item

With the above, for example, you can grep for a specific menu item title, and then use something like awk to retrieve the parent menu item ID.

Does that provide what you need, or are you thinking of something else specifically?

schlessera avatar Dec 01 '18 19:12 schlessera

Hi schlessera,

Thanks for your response. Unfortunately no :( I will try to explain this with code, for example I want to get specific menu item where page title name or page slug is shop

wp menu item get main-menu --slug=shop --fields=db_id,title

and results will be for example db_id title
101 Shop

then I want to grab that ID and to add additional pages to it as child menu items

wp menu item add-post main-menu 102 --title="Custom Menu Item" --parent-id=101

I hope I explained it to you.

Best regards, Nenad

NenadObradovic avatar Dec 06 '18 13:12 NenadObradovic

Hi schlessera,

Example function for that

wp menu item get main-menu --menu-item-title="Shop"

public function get( $args, $assoc_args ) {
	$item_id = 0;
	$items   = wp_get_nav_menu_items( $args[0] );
	
	if ( false === $items || is_wp_error( $items ) ) {
		WP_CLI::error( "Invalid menu." );
	}
	
	if ( ! empty( $assoc_args['menu-item-title'] ) ) {
		foreach ( $items as $item ) {
			if ( $item->title === $assoc_args['menu-item-title'] ) {
				$item_id = $item->ID;
				break;
			}
		}
	} else {
                WP_CLI::error( "Menu item title is invalid." );
        }
	
	return (int) $item_id;
}

Best regards, Nenad

NenadObradovic avatar Dec 25 '18 14:12 NenadObradovic