4

I am trying to add an image to the header.php navigation using Advanced Custom Fields PRO, However, it does not show up. I have tried various solutions such as (in functions.php):

add_filter('wp_nav_menu_items', 'my_wp_nav_menu_items', 10, 2);

function my_wp_nav_menu_items( $items, $args ) {

    $menu = wp_get_nav_menu_object($args->menu);
    
    if( $args->theme_location == 'top' ) {
        
        $logo = get_field('logo', $menu);
        $color = get_field('color', $menu);
        
        $html_logo = '<li class="menu-item-logo"><a href="'.home_url().'"><img src="'.$logo['url'].'" alt="'.$logo['alt'].'" class="logo" /></a></li>';
        
        $html_color = '<style type="text/css">.navigation-top{ background: '.$color.';}</style>';
        
        $items = $html_logo . $items . $html_color; 
    }
    return $items;
}

I have tried to print out the args array but it shows up as empty.

Second solution I've tried (in header.php):

<?php $image = get_field('logo'); ?>
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" class="logo" />

Thank you in advance <3

edit: Ive also tried using:

        <?php
global $wp_query;
$postid = $wp_query->post->ID;
echo get_post_meta($postid, 'logo', true);
wp_reset_query();
?>

bot there is no output. If I change it from true to false I just get an empty array [1]: https://i.stack.imgur.com/03u0H.png [2]: https://i.stack.imgur.com/ahcqf.jpg

qulpe
  • 41
  • 2
  • 1
    Where is the field being set? Is it on an options page? On a category? A specific post/page? – DubVader Jan 06 '21 at 17:15
  • Also, a screenshot of the ACF field on the page in question might be helpful. If `var_dump()` shows nothing, it means you have to take a step back and go through the process again. – thaikolja Jan 06 '21 at 23:13
  • 2
    I've added links with pictures of my acf fields. I am targeting a specific menu. (changing the rule from menu item to menu does not change anything). @thaikolja – qulpe Jan 07 '21 at 08:56
  • @DubVader I am targeting a menu – qulpe Jan 07 '21 at 08:59
  • I prefer to use the image URL option (instead of array) when I'll be implementing the image in the way you are here. It returns the URL and then you put it into the `` tag and bingo bango – JDawwgy Aug 24 '22 at 23:38

1 Answers1

1

You've passed $menu in get_field function instead of location of field :)

$logo = get_field('logo', 'locationGoesHere');

Always use e.g. var_dump($logo); to check if you retrieving anything from database, if you fail at that point then you shouldn't look any further than that :D If you are unsure about location of your field you've created then go to tools in ACF and "export" your options to JSON/PHP -> look for your field logo and below that nested field you should have key 'location'.

NipponDEV
  • 46
  • 3