最好的解决方案是允许用户在添加/编辑页面时选择导航菜单位置。使用带有下拉列表(select)的元框,选择所有可用位置,然后将所选位置保存在自定义字段中:
/**
* Register the meta box.
*/
function wpse_183868_page_nav_menu_meta_box_register() {
add_meta_box(
\'wpse_183868_page_nav_menu\',
\'Nav Menu\',
\'wpse_183869_page_nav_menu_meta_box\',
\'page\',
\'side\'
);
}
add_action( \'add_meta_boxes\', \'wpse_183868_page_nav_menu_meta_box_register\' );
/**
* Display the meta box.
*/
function wpse_183869_page_nav_menu_meta_box( $post ) {
$selected = get_post_meta( $post->ID, \'_page_nav_menu\', true );
wp_nonce_field( \'save\', \'page_nav_menu_nonce\' );
?>
<select name="page_nav_menu">
<?php foreach ( get_registered_nav_menus() as $name => $label ) : ?>
<option value="<?php echo $name ?>"<?php selected( $name, $selected ) ?>><?php echo $label ?></option>
<?php endforeach ?>
</select>
<?php
}
/**
* Save the meta box data.
*/
function wpse_183869_page_nav_menu_save( $post_id ) {
if ( ! isset( $_POST[\'page_nav_menu\'], $_POST[\'page_nav_menu_nonce\'] ) || ! wp_verify_nonce( $_POST[\'page_nav_menu_nonce\'], \'save\' ) )
return;
$nav_menus = get_registered_nav_menus();
$nav_menu = $_POST[\'page_nav_menu\'];
if ( isset( $nav_menus[ $nav_menu ] ) ) // Paranoid - check the submitted value is definitely valid
update_post_meta( $post_id, \'_page_nav_menu\', $nav_menu );
}
add_action( \'save_post\', \'wpse_183869_page_nav_menu_save\' );
现在,您可以在模板中使用:
if ( ! $page_nav_menu = get_post_meta( get_the_ID(), \'_page_nav_menu\', true ) )
$page_nav_menu = \'default_location\';
wp_nav_menu( array( \'theme_location\' => $page_nav_menu ) );