Skip to content

Instantly share code, notes, and snippets.

@willgorham
Last active September 29, 2018 00:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save willgorham/8131f63f11fb48c5def1155f5c277120 to your computer and use it in GitHub Desktop.
Save willgorham/8131f63f11fb48c5def1155f5c277120 to your computer and use it in GitHub Desktop.
WordPress: Set specific menus (theme locations) to auto-add pages
<?php
/**
* Allows programatically seting of specific menu locations (or more specifically,
* the menus assigned to those locations) to automatically add new pages.
* [I.e. enables the 'Automatically add new top-level pages to this menu' setting]
*
* Usage (via WP CLI):
* - Add file to mu-plugins folder (might also work in functions.php?)
* - Get theme menu location slugs you want to enable auto-added pages (e.g. 'home' and 'footer-nav')
* - From the command line (SSH or otherwise), call:
*
* wp set-auto-add-menus home footer-nav
*
* For multisite usage:
*
* wp site list --field=url | xargs -n1 -I % wp --url=% set-auto-add-menus home footer-nav
*
*/
if ( ! class_exists( 'WP_CLI' ) ) {
return;
}
$set_auto_add_menus = function( $args, $assoc_args ) {
$theme_locations = get_nav_menu_locations();
$menus_to_auto_add = array();
$nav_menu_options = get_option( 'nav_menu_options', array() );
if ( ! isset( $nav_menu_options['auto_add'] ) ) {
$nav_menu_options['auto_add'] = array();
}
foreach( $args as $menu_name ) {
if ( isset( $theme_locations[$menu_name] ) && $theme_locations[$menu_name] ) {
$menus_to_auto_add[] = $theme_locations[$menu_name];
}
}
foreach( $menus_to_auto_add as $menu_id ) {
if ( ! in_array( $menu_id, $nav_menu_options['auto_add'] ) ) {
$nav_menu_options['auto_add'][] = $menu_id;
}
}
$update = update_option( 'nav_menu_options', $nav_menu_options );
// Useful for multisite application.
if ( $update ) {
WP_CLI::success( home_url('/') );
} else {
WP_CLI::warning( home_url('/') );
}
};
WP_CLI::add_command( 'set-auto-add-menus', $set_auto_add_menus );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment