Here's my code now:
$menu_icon = get_field('menu_icon');
if($menu_icon) {
$m_icon = '<img src="'.the_field('menu_icon').'">';
} else {
$m_icon = "";
};
$personal = array(
'theme_location' => 'personal',
'menu' => 'Personal Menu',
'before' => '$m_icon',
);
wp_nav_menu( $personal );
And here's what it spits out:
<ul id="menu-personal-menu" class="menu">
<li class="menu-item>
$m_icon <a href="#">Link</a>
<ul class="sub-menu">
<li>$m_icon <a href="#1">SubLink 1</a></li>
<li>$m_icon <a href="#2">SubLink 2</a></li>
<li>$m_icon <a href="#3">SubLink 3</a></li>
</ul>
</li>
</ul>
I'd like to have it produce something like this:
<ul id="menu-personal-menu" class="menu">
<li class="menu-item>
<a href="#">Link</a>
<ul class="sub-menu">
<li><img src="path/sublinkimg1"> <a href="#1">SubLink 1</a></li>
<li><img src="path/sublinkimg2"> <a href="#2">SubLink 2</a></li>
<li><img src="path/sublinkimg3"> <a href="#3">SubLink 3</a></li>
</ul>
</li>
</ul>
Here's the general idea:
It's wrong for a few reasons. I know the advanced custom field: "menu_icon" probably isn't able to retrieve anything outside of a loop, and I'm not familiar enough with the wp_nav_menu() function to know whether or not it's possible to echo an image specific to the page it's displaying.
Does anyone know how I can achieve this?
One thing I notice right away is that you have extra single quotes, and php is translating the content literally. You actually want the string contained in $m_icon, and NOT the string '$m_icon' which is not a variable.
$personal = array(
'theme_location' => 'personal',
'menu' => 'Personal Menu',
'before' => $m_icon, //this line was wrong, single quotes means 'literally this$ $tring'
);
Edit: I took the liberty of writing a filter function for what you're trying to do. Cheers.
function insert_icons($items, $menu, $args){
//check our menu name so we filter the right one
if($menu->name=='Personal Menu'){
//loop through the menu items
foreach($items as $key => $item){
//make sure object_id is set (this is the page or post id)
if(isset($item->object_id) && !empty($item->object_id)){
//grab the menu icon
$menu_icon = get_field('menu_icon',$item->object_id);
//make sure the previous line returned something
if(isset($menu_icon) && !empty($menu_icon)){
//create our image string
$m_icon = '<img src="'.$menu_icon.'">';
//insert it into the page title
$item->title = $m_icon.$item->title;
}
}
}
}
return $items;
}
add_filter('wp_get_nav_menu_items','insert_icons',NULL,3);
Not exactly what you asked for and i don't have the correct solution for your entire problem right now but i can help you with getting custom fields to work outside the loops if that helps you :)
you just have to set the page ID after your field name for it to work outside of loop like this
get_field('your-field', $page_ID);