web-dev-qa-db-fra.com

Attribuer des menus à des emplacements de thème avec activation de thème

Un site utilise le thème enfant nommé "enfant1". Lorsque ce site bascule sur un autre thème enfant nommé "enfant2", leurs widgets sont également déplacés, mais les emplacements de thème ne le sont pas. Comment puis-je attribuer automatiquement des menus à des emplacements de thème lors de l'activation de thème?

J'ai trouvé cette solution de http://wordpress.org/support/topic/how-to-assign-a-wordpress-3-menu-to-primary-location-programmatically

$theme = get_current_theme();
$mods = get_option("mods_$theme");
$key = key($mods['nav_menu_locations']);
$mods['nav_menu_locations'][$key] = $menu_id;
update_option("mods_$theme", $mods);

Existe-t-il un meilleur moyen wordpress pour résoudre ce problème? (Sujet de transaction associé: http://core.trac.wordpress.org/ticket/18720 )

3
Ünsal Korkmaz

Eh bien, j'ai écrit une solution, écrivez-la ici:

/* 
 This action copies old theme's theme location saves to 
 new theme if new theme doesnt have saves before.
 */
 add_action( 'after_switch_theme',  'ajx_theme_locations_rescue' );
 function ajx_theme_locations_rescue() {
    // bug report / support: http://www.unsalkorkmaz.com/
    // We got old theme's slug name
    $old_theme = get_option( 'theme_switched' );
    // Getting old theme's settings
    $old_theme_mods = get_option("theme_mods_{$old_theme}");
    // Getting old theme's theme location settings
    $old_theme_navs = $old_theme_mods['nav_menu_locations'];
    // Getting new theme's theme location settings
    $new_theme_navs = get_theme_mod( 'nav_menu_locations' );

    // If new theme's theme location is empty (its not empty if theme was activated and set some theme locations before)
    if (!$new_theme_navs) {
        // Getting registered theme locations on new theme
        $new_theme_locations = get_registered_nav_menus();

        foreach ($new_theme_locations as $location => $description ) {
            // We setting same nav menus for each theme location 
            $new_theme_navs[$location] = $old_theme_navs[$location];
        }

        set_theme_mod( 'nav_menu_locations', $new_theme_navs );

    }
 }
3
Ünsal Korkmaz

Je sais que vous avez ce problème il y a longtemps, mais depuis que ce site est apparu avec les premiers, j'ai pensé partager ma solution au cas où quelqu'un en aurait besoin.

0
Rochelle Cassar