Skip to content

Instantly share code, notes, and snippets.

@vovadocent
Created September 20, 2018 14:27
Show Gist options
  • Save vovadocent/57d0f1dcadfd07e9404f0be1ed5c19e0 to your computer and use it in GitHub Desktop.
Save vovadocent/57d0f1dcadfd07e9404f0be1ed5c19e0 to your computer and use it in GitHub Desktop.
Add background-image or background-color to nav menu item using ACF
<?php
//add background-image or background-color to nav menu item using ACF
add_filter('wp_nav_menu_items', 'new_nav_menu_items', 10, 2);
function new_nav_menu_items($items, $args) {
preg_match_all('/menu-item-([0-9]{1,10})"/ ', $items, $matches);
if (isset($matches[0]) && isset($matches[1])) {
foreach ($matches[0] as $k => $repl) {
$post_id = $matches[1][$k];
if ($image_id = get_field('image_menu', $post_id))
$st = "style='". image_src($image_id, 'free', 1) ."' ";
elseif($bg = get_field('background_color_menu', $post_id))
$st = "style='background-color: $bg' ";
else
$st = "";
$items = str_replace($repl, "$repl $st ", $items);
}
}
return $items;
}
@gray4444
Copy link

gray4444 commented Apr 7, 2020

nice

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment