WordPress菜单-Ajax加载

Is it possible to dynamically load Wordpress menu via Ajax?

Best solution would be using wp_nav_menu().

You can create a custom file to handle ajax requests in your theme, returning the HTML output of wp_nav_menu(); and call that file.

wp-content/themes/your-theme/ajax.php:

<?php wp_nav_menu(); ?>

It's simple, but efficient. Be careful with security though. Make sure to validate input and dont eval() any input!

If your theme needs to dynamically initialize menus with JavaScript, the pattern for the initialization code should be:

jQuery(function($) {
    function initMainNavigation( container ) {
        /* set up container... */
    }
    initMainNavigation( $( '.main-navigation' ) );

    $( document ).on( 'customize-preview-menu-refreshed', function( e, params ) {
        if ( 'primary' === params.wpNavMenuArgs.theme_location ) {
            initMainNavigation( params.newContainer );
            /* optionally sync a previous menu state from params.oldContainer... */
        }
    });
});

The params being passed to the event handler consists of the following properties:

  • newContainer: jQuery object containing the new menu container element retrieved from Ajax; this is what you would manipulate to initialize.

  • oldContainer: the previous jQuery object holding the element for the replaced menu container; this is useful if there is any state in the old menu that should persist in the new menu, such as which submenus are expanded (as in Twenty Fifteen).

  • wpNavMenuArgs: The array of arguments passed to wp_nav_menu() in the template, such as template_location.

  • instanceNumber: The index for which wp_nav_menu() call being updated.