Skip to content

Instantly share code, notes, and snippets.

@anwerashif
Created November 24, 2019 12:35
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 anwerashif/94e64829d42ae5ab0dd6b5de12027a58 to your computer and use it in GitHub Desktop.
Save anwerashif/94e64829d42ae5ab0dd6b5de12027a58 to your computer and use it in GitHub Desktop.
<?php
$fields = array (
'field-01' => __( 'Icon URL', 'menu-item-custom-icon_field' ),
'field-02' => __( 'New Field', 'menu-item-custom-new_field' ),
);
// funtion to add fields to menu item
function add_menuset_c_fields( $id, $item, $depth, $args ) {
global $fields;
foreach ( $fields as $_key => $label ) :
$key = sprintf( 'menu-item-%s', $_key );
$id = sprintf( 'edit-%s-%s', $key, $item->ID );
$name = sprintf( '%s[%s]', $key, $item->ID );
$value = get_post_meta( $item->ID, $key, true );
$class = sprintf( 'field-%s', $_key );
?>
<p class="description description-wide <?php echo esc_attr( $class ) ?>">
<?php printf(
'<label for="%1$s">%2$s<br /><input type="text" id="%1$s" class="widefat %1$s" name="%3$s" value="%4$s" /></label>',
esc_attr( $id ),
esc_html( $label ),
esc_attr( $name ),
esc_attr( $value )
) ?>
</p>
<?php
endforeach;
}
add_action( 'wp_nav_menu_item_custom_fields', 'add_menuset_c_fields', 10, 4 );
// function to save custom fields
function save_menuset_c_fields( $menu_id, $menu_item_db_id, $menu_item_args ) {
if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
return;
}
global $fields;
check_admin_referer( 'update-nav_menu', 'update-nav-menu-nonce' );
foreach ( $fields as $_key => $label ) {
$key = sprintf( 'menu-item-%s', $_key );
// Sanitize
if ( ! empty( $_POST[ $key ][ $menu_item_db_id ] ) ) {
// Do some checks here...
$value = $_POST[ $key ][ $menu_item_db_id ];
} else {
$value = null;
}
// Update
if ( ! is_null( $value ) ) {
update_post_meta( $menu_item_db_id, $key, $value );
} else {
delete_post_meta( $menu_item_db_id, $key );
}
}
}
add_action( 'wp_update_nav_menu_item', 'save_menuset_c_fields', 10, 3 );
// function to add them to screen
function columns_menuset_c_fields( $columns ) {
global $fields;
$columns = array_merge( $columns, $fields );
return $columns;
}
add_filter( 'manage_nav-menus_columns', 'columns_menuset_c_fields', 99 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment