This code snippet below is for adding custom fields to WordPress menu items based on login status. When editing a menu item in the WordPress admin, this function inserts a dropdown selector labeled “Login Status”
function add_custom_fields_to_menu_item($item_id, $item)
{
// Get the values of the custom fields
$login_status_value = get_post_meta($item_id, 'login_status', true);
// Add nonce field for security
wp_nonce_field('save_menu_custom_fields_' . $item_id, 'menu_custom_fields_nonce_' . $item_id);
// Get all available user roles
global $wp_roles;
$roles = $wp_roles->roles;
$current_user = wp_get_current_user();
?>
<p class="description description-wide">
<label for="edit-menu-item-login-status-<?php echo esc_attr($item_id); ?>"><?php esc_html_e('Login Status:', 'wporg'); ?></label>
<select id="edit-menu-item-login-status-<?php echo esc_attr($item_id); ?>" name="menu-item-custom-field[<?php echo esc_attr($item_id); ?>][login_status]">
<option value="none" <?php selected($login_status_value, 'none'); ?>><?php esc_html_e('Show All', 'wporg'); ?></option>
<option value="logged_in" <?php selected($login_status_value, 'logged_in'); ?>><?php esc_html_e('If Logged In', 'wporg'); ?></option>
<option value="not_logged_in" <?php selected($login_status_value, 'not_logged_in'); ?>><?php esc_html_e('If Not Logged In', 'wporg'); ?></option>
</select>
</p>
<?php
}
add_action('wp_nav_menu_item_custom_fields', 'add_custom_fields_to_menu_item', 10, 2);Then The function filter_menu_items_by_user_role modifies WordPress navigation menu items based on user roles and login status. It begins by retrieving the current user’s roles using wp_get_current_user() and then iterates through each menu item passed into it.
Then last, this function below, save_menu_custom_fields handles the saving of custom fields associated with WordPress menu items. It first verifies the security nonce to prevent unauthorized access or tampering. If the nonce verification fails, the function exits early.

