wordpress - PHP error with versions 7.4+ ValueError: Unknown format specifier "C" in
Why am I getting sprintf(): Too few arguments here php error here while trying to use this in items_wrap on wp_nav_menu()?
$menu = wp_get_nav_menu_object('primary-menu');
$navId = $menu->term_id;
$menuId = 'menu_' . $navId;
$navUrl = get_field('social_media_url', $menuId);
$navImg = get_field('social_media_img', $menuId);
if ($navUrl && $navImg) {
$socialOption = '<ul id="%s" class="%s">%s<li class="menu-social-option"><a href="' . esc_attr($navUrl) . '" target="_blank"><img src="' . esc_attr($navImg['url']) . '"></a></li></ul>';
} else {
$socialOption = '<ul id="%1$s" class="%2$s">%3$s</ul>';
}
$navArray = array(
'theme_location' => 'primary', // Defined when registering the menu
'menu_id' => 'primary-menu',
'container' => false,
'depth' => 2,
'items_wrap' => $socialOption,
'menu_class' => 'navbar-nav ml-auto',
'walker' => new Bootstrap_NavWalker(), // This controls the display of the Bootstrap Navbar
'fallback_cb' => 'Bootstrap_NavWalker::fallback', // For menu fallback
);
wp_nav_menu($navArray);
When I remove esc_url($navUrl) then I get this type of error uncaught ValueError: Unknown format specifier "C" in. This only happens with PHP versions 7.4+
Cheers
Answer
Solution:
My solution to this issue. Turns out I don't have to use sprintf again. To wrap an extra item to wp_nav_menu with ACF variables I use this function. If any of ACF variables are empty then it just returns $items which is set by Wordpress.
function add_last_nav_item($items)
{
$menu = wp_get_nav_menu_object('primary-menu');
$navId = $menu->term_id;
$menuId = 'menu_' . $navId;
$navUrl = get_field('social_media_url', $menuId);
$navImg = get_field('social_media_img', $menuId);
if ($navUrl && $navImg) {
return $items .= '<li class="menu-social-option"><a href="' . esc_attr($navUrl) . '" target="_blank"><img src="' . esc_attr($navImg['url']) . '"></a></li>';
} else {
return $items;
}
}
add_filter('wp_nav_menu_items', 'add_last_nav_item');
$socialOption = '<ul id="%1$s" class="%2$s">%3$s</ul>';
Thank you @RiggsFolly for helping me figure this out
Source