To create a dynamic, WordPress-compliant menu system, use this complete functional code to register navigation locations and display menus:
// Add to your theme's functions.php file
function register_dynamic_wordpress_menus() {
// Register custom menu positions
register_nav_menus([
'primary_nav' => __('Primary Header Menu', 'your-theme-text-domain'),
'footer_nav' => __('Footer Links Menu', 'your-theme-text-domain')
]);
}
add_action('init', 'register_dynamic_wordpress_menus');
// Helper function to display your primary menu
function display_primary_menu() {
if (has_nav_menu('primary_nav')) {
wp_nav_menu([
'theme_location' => 'primary_nav',
'menu_class' => 'custom-primary-menu',
'container' => 'nav',
'container_class'=> 'site-header-navigation',
'depth' => 2, // Show up to 2 levels of submenus
'fallback_cb' => false
]);
}
}
// Helper function to display your footer menu
function display_footer_menu() {
if (has_nav_menu('footer_nav')) {
wp_nav_menu([
'theme_location' => 'footer_nav',
'menu_class' => 'custom-footer-menu',
'container' => 'div',
'container_class'=> 'footer-menu-container',
'depth' => 1 // No submenus for footer
]);
}
}
To use these menus in your theme:
- In the template where you want the primary menu (e.g., header.php), add
<?php display_primary_menu(); ?> - In your footer template, add
<?php display_footer_menu(); ?> - Navigate to WordPress Dashboard → Appearance → Menus to create/edit menus and assign them to the registered locations.
This follows WordPress best practices for dynamic menu management, allowing full control over menu structure from the admin dashboard.


作者声明:本文包含人工智能生成内容。