Instantly share code, notes, and snippets.
Created
April 17, 2012 03:54
Allow choosing of a custom menu and saving that value as postmeta
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Show custom menus as select list | |
* For use with CMB for WP: https://github.com/jaredatch/Custom-Metaboxes-and-Fields-for-WordPress/wiki/Adding-your-own-field-types | |
* @author Travis Northcutt | |
* @link https://gist.github.com/2284508 | |
* | |
* @param array $field | |
* @param string $meta | |
* | |
*/ | |
add_action( 'cmb_render_custom_menu', 'ba_cmb_render_custom_menu', 10, 2 ); | |
function ba_cmb_render_custom_menu( $field, $meta ) { | |
$menus = get_terms( 'nav_menu', array( 'hide_empty' => false ) ); | |
if ( !$menus ) { | |
echo '<p>'. sprintf( __('No menus have been created yet. <a href="%s">Create some</a>.'), admin_url('nav-menus.php') ) .'</p>'; | |
return; | |
} | |
echo '<select name="', $field['id'], '" id="', $field['id'], '">'; | |
echo '<option value="">None</option>'; | |
foreach ( $menus as $menu ) { | |
echo '<option value="', $menu->term_id, '"', $meta == $menu->term_id ? ' selected="selected"' : '', '>', $menu->name, '</option>'; | |
} | |
echo '</select>'; | |
echo '<p class="cmb_metabox_description">', $field['desc'], '</p>'; | |
} | |
/** | |
* Add filter to make the newly defined custom_menu meta field work with CMB for WP | |
* forked from Travis Northcutt's gist: https://gist.github.com/2284508 | |
* @author Pat Ramsey | |
* | |
* 'type' is set to the latter part of the cmb_render_ action created above. In this case 'custom_menu' | |
* | |
*/ | |
add_filter( 'cmb_meta_boxes', 's25_menu_meta_boxes' ); | |
function s25_menu_meta_boxes( $meta_boxes ) { | |
$meta_boxes[] = array ( | |
'id' => 's25_menu_box', | |
'title' => 'Custom Menu', | |
'pages' => array ( 'page' ), | |
'context' => 'normal', | |
'priority' => 'high', | |
'show_names' => true, // Show field names on the left | |
'fields' => array ( | |
array ( | |
'name' => 'Custom Menu', | |
'id' => 's25_custom_menu', | |
'type' => 'custom_menu', | |
'desc' => 'Invalid email addresses will be wiped out.' | |
) | |
) | |
); | |
return $meta_boxes; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment