To add a checkbox in the extended properties of a menu in WordPress, you need to use hooks and WordPress API functions to create and process additional fields. Here’s an example of how to do this:
Adding a checkbox to the menu edit form
Use the hook wp_nav_menu_item_custom_fields
to add the field in the menu edit form:
add_action('wp_nav_menu_item_custom_fields', 'add_custom_checkbox_field', 10, 4);
function add_custom_checkbox_field($item_id, $item, $depth, $args) {
$custom_checkbox = get_post_meta($item_id, '_custom_checkbox', true);
?>
<p class="field-custom field-custom-checkbox description-wide">
<label for="edit-menu-item-custom-checkbox-<?php echo $item_id; ?>">
<input type="checkbox" id="edit-menu-item-custom-checkbox-<?php echo $item_id; ?>" name="menu-item-custom-checkbox[<?php echo $item_id; ?>]" value="1" <?php checked($custom_checkbox, 1); ?> />
<?php _e('Custom Checkbox', 'text-domain'); ?>
</label>
</p>
<?php
}
Saving the checkbox value
Use the hook wp_update_nav_menu_item
to save the checkbox value when saving the menu:
add_action('wp_update_nav_menu_item', 'save_custom_checkbox_field', 10, 3);
function save_custom_checkbox_field($menu_id, $menu_item_db_id, $args) {
if (isset($_POST['menu-item-custom-checkbox'][$menu_item_db_id])) {
$custom_checkbox = 1;
} else {
$custom_checkbox = 0;
}
update_post_meta($menu_item_db_id, '_custom_checkbox', $custom_checkbox);
}
Using the checkbox value
If you want to use the checkbox value in your menu template, you can retrieve it using get_post_meta
:
$custom_checkbox = get_post_meta($item->ID, '_custom_checkbox', true);
if ($custom_checkbox) {
// Your code to display or use the checkbox
}
This code adds a checkbox to the extended properties section of each menu item, saves its value, and allows you to use this value in your template. Don’t forget to replace 'text-domain'
with your text domain.