Created
April 8, 2025 02:29
-
-
Save westcoastdigital/bba170c2994c5b5f904c2cbf20d2657f to your computer and use it in GitHub Desktop.
How to add a custom field to WordPress menu item on specific registered menu
This file contains hidden or 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
/* | |
* WP Version: 6.7.2 | |
*/ | |
// Add the checkbox to the menu item custom fields only for main-menu | |
function wcd_add_product_categories_checkbox($item_id, $item) { | |
// Get the global menu variable that holds the current menu being edited | |
global $nav_menu_selected_id; | |
// Get all menu locations | |
$locations = get_nav_menu_locations(); | |
// Menu ID to check against | |
$menu_id = 'main-menu'; // Replace with your menu ID if different | |
// Check if current menu is assigned to menu_id location | |
$is_menu_id = false; | |
if (isset($locations[$menu_id]) && $locations[$menu_id] == $nav_menu_selected_id) { | |
$is_menu_id = true; | |
} | |
// Only show the checkbox if it's the menu_id | |
if ($is_menu_id) { | |
wp_nonce_field('add_product_categories_nonce', '_add_product_categories_nonce_name'); | |
$checked = get_post_meta($item_id, '_add_product_categories', true); | |
?> | |
<p class="field-add-product-categories description description-wide"> | |
<label for="edit-menu-item-add-product-categories-<?php echo $item_id; ?>"> | |
<input type="checkbox" id="edit-menu-item-add-product-categories-<?php echo $item_id; ?>" name="menu-item-add-product-categories[<?php echo $item_id; ?>]" <?php echo checked($checked, 'on', false); ?> /> | |
<?php esc_html_e('Add Product Categories as Submenu', 'your-theme'); ?> | |
</label> | |
</p> | |
<?php | |
} | |
} | |
add_action('wp_nav_menu_item_custom_fields', 'wcd_add_product_categories_checkbox', 10, 2); | |
// Save the checkbox data when updating the menu item | |
function wcd_save_product_categories_checkbox($menu_id, $menu_item_db_id) { | |
if (!isset($_POST['_add_product_categories_nonce_name']) || !wp_verify_nonce($_POST['_add_product_categories_nonce_name'], 'add_product_categories_nonce')) { | |
return; | |
} | |
// Check if the checkbox was ticked | |
if (isset($_POST['menu-item-add-product-categories'][$menu_item_db_id])) { | |
$checked = 'on'; | |
} else { | |
$checked = 'off'; | |
} | |
// Save the checkbox value in post meta for the menu item | |
update_post_meta($menu_item_db_id, '_add_product_categories', $checked); | |
} | |
add_action('wp_update_nav_menu_item', 'wcd_save_product_categories_checkbox', 10, 2); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment