Reputation: 11
I have a custom walker for my navigation menu, inside which I want to get the menu item custom field value to further customize my menu items. Here is my code..
My menu item custom field is menu-item-mymenucolor
and I want to get its value in $menu_color
(currently I get blank!)
wp_nav_menu( array(
'menu' => 'primary',
'walker' => new WPDocs_Walker_Nav_Menu()
)
);
// Custom Nav Menu walker class.
class WPDocs_Walker_Nav_Menu extends Walker_Nav_Menu {
function start_lvl( &$output, $depth = 0, $args = array() ) {
// Depth-dependent classes.
$indent = ( $depth > 0 ? str_repeat( "\t", $depth ) : '' ); // code indent
$display_depth = ( $depth + 1); // because it counts the first submenu as 0
// Custom nav menu item custom field value i want to get in the $classes.
$menu_color = '"style="background-color: '.get_post_meta($item->ID, 'menu-item-mymenucolor', true).';';
// Combine values of classes.
$classes = array(
'dropdown-menu',
( $display_depth % 2 ? 'menu-odd' : 'menu-even' ),
( $display_depth >=2 ? 'sub-sub-menu' : '' ),
'menu-depth-' . $display_depth,
''. $menu_color
);
$class_names = implode( ' ', $classes );
// Build HTML for output.
$output .= ($depth == 0) ? "\n" . $indent . '<ul class="' . $class_names . '">' . "\n" . "\n <div class=\"megamenu-content\">\n" . "\n<div class=\"row\">\n" : "\n<ul class=\"elementy-ul\">\n";
}
// Start the element output codes from here.....
}
Actually I can easily get the value of Woocommerce in the $menu_color
place by just inserting the $woocommerce global variable, so is there anything to do with global variables? here take a look at this,
global $woocommerce;
// get cart quantity
$cart_qty = $woocommerce->cart->get_cart_contents_count();
$classes = array(
'dropdown-menu',
( $display_depth % 2 ? 'menu-odd' : 'menu-even' ),
( $display_depth >=2 ? 'sub-sub-menu' : '' ),
'menu-depth-' . $display_depth,
''. $cart_qty
);
Whereas, its much easier to get the menu item custom field value inside start element of this walker section, I will just post an important part of the code to make it short. I hope you understand where it must have been..
$item_output .= '<a'. $attributes .' style="background-color: '.get_post_meta($item->ID, 'menu-item-mymenucolor', true).';">';
$item_output .= '</a>';
I have tried almost every possibilities to get the value but none could work as of now. I know this will absolutely work like a charm, but I think i am missing something important here.
So, Is there any way this can be achieved?
Thanks!
Upvotes: 1
Views: 1172
Reputation: 11480
You need to use $item->object_id
instead of $item->ID
and everything will work fine.
Maybe this is a late answer but since no one answered till now I thought it's a good idea to answer it, maybe it will help someone else too.
Upvotes: 3