public
Last active

add post to nav menu

  • Download Gist
functions.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84
<?php
add_action( 'add_meta_boxes', 'add_custom_box_wpse_87594' );
add_action( 'save_post', 'save_postdata_wpse_87594', 10, 2 );
 
function add_custom_box_wpse_87594()
{
add_meta_box(
'section_id_wpse_87594',
__( 'Available Nav-Menus' ),
'inner_custom_box_wpse_87594',
'post',
'side',
'high'
);
}
 
function inner_custom_box_wpse_87594()
{
$navmenus = wp_get_nav_menus( array( 'hide_empty' => false, 'orderby' => 'none' ) );
 
// DEBUG
// echo '<pre>' . print_r( $navmenus, true ) . '</pre>';
 
wp_nonce_field( plugin_basename( __FILE__ ), 'noncename_wpse_87594' );
 
echo '<select name="nav_menus_dropdown" id="nav_menus_dropdown">
<option value="">- Select -</option>';
 
foreach( $navmenus as $m )
{
echo "<optgroup label='$m->name'>";
echo "<option value={$m->term_id}>&#8593; Add on top</option>";
$items = wp_get_nav_menu_items( $m->term_id);
foreach ($items as $key => $menu_item ) {
if(!$menu_item->menu_item_parent){
printf('<option value="%s-%s">%s</option>',
$m->term_id,
$menu_item->object_id,
$menu_item->title);
}
echo "</optgroup>";
}
 
echo '</select>';
}
}
 
function save_postdata_wpse_87594( $post_id, $post_object )
{
// Auto save?
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
 
// Security
if (
!isset( $_POST['noncename_wpse_87594'] )
|| !wp_verify_nonce( $_POST['noncename_wpse_87594'], plugin_basename( __FILE__ ) )
)
return;
 
// Correct post_type
if ( 'post' != $post_object->post_type )
return;
 
if( !empty( $_POST['nav_menus_dropdown'] ) )
{
$parents = explode('-', $_POST['nav_menus_dropdown']);
$item = array(
'menu-item-title' => $_POST['post_title'],
'menu-item-object' => 'page',
'menu-item-object-id' => $_POST['ID'],
'menu-item-type' => 'post_type',
'menu-item-status' => 'publish'
);
if(count($parents) > 1){
$item['menu-item-parent-id'] = $parents[1];
}
wp_update_nav_menu_item(
$_POST['nav_menus_dropdown'],
0,
$item
);
}
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.