Could we help you? Please click the banners. We are young and desperately need the money
WordPress menus are a core part of website navigation. However, they often rely on static data, limiting their flexibility. With Advanced Custom Fields (ACF), you can dynamically populate menu items based on custom fields, creating a more versatile and user-friendly experience.
ACF allows you to add custom fields to various parts of your WordPress site, including posts, pages, and even users. Integrating these fields into WordPress menus enables you to:
Imagine you’re building a website for a real estate agency. Each property has a dedicated page, and the navigation menu should display featured properties dynamically. Using ACF, you can set up a custom field for featured properties and populate the menu accordingly.
Add the following PHP code to your theme’s functions.php file to dynamically populate menu items based on the custom field:
add_filter('wp_nav_menu_items', function($items, $args) {
// Check if the menu location matches your desired menu
if ($args->theme_location === 'primary') {
// Get the featured properties from the custom field
$featured_properties = get_field('featured_properties', 'option');
if ($featured_properties) {
foreach ($featured_properties as $property) {
$items .= sprintf(
'<li><a href="%s">%s</a></li>',
get_permalink($property),
get_the_title($property)
);
}
}
}
return $items;
}, 10, 2);
If your theme doesn’t already register a menu location, add this to functions.php:
register_nav_menus([
'primary' => __('Primary Menu', 'your-theme')
]);
Did you know that you can also assign custom ACF fields directly to WordPress menu items? This is especially useful for adding metadata, icons, or tooltips to individual menu items. To enable this:
add_filter('walker_nav_menu_start_el', function($item_output, $item, $depth, $args) {
$icon_class = get_field('menu_item_icon', $item);
if ($icon_class) {
$item_output = sprintf(
' %s',
esc_url($item->url),
esc_attr($icon_class),
esc_html($item->title)
);
}
return $item_output;
}, 10, 4);
Integrating ACF with WordPress menus opens up endless possibilities for dynamic and tailored navigation. Whether you’re building a real estate site, an e-commerce store, or a personal blog, this approach enhances usability and engagement.
You can even extend functionality further by adding ACF fields directly to menu items, enabling highly customizable and feature-rich menus. Start using ACF with WordPress menus today and take your site navigation to the next level!