<?php 

/**
 * Abilita custom field per Iubenda popup nei menu
 */
function laniakea_menu_item_iubenda($item_id, $item)
{
    $menu_item_iubenda = get_post_meta($item_id, '_menu_item_iubenda', true);

?>
    <div style="clear: both;">
        <label for="menu-item-iubenda-<?php echo $item_id; ?>">Iubenda Popup</label>
        <input type="hidden" class="nav-menu-id" value="<?php echo $item_id; ?>" />
        <div class="logged-input-holder">
            <input type="checkbox" name="_menu_item_iubenda[<?php echo $item_id; ?>]" id="menu-item-iubenda-<?php echo $item_id; ?>" value="1" <?php checked($menu_item_iubenda, 1, true); ?> />
        </div>
    </div>
<?php
}
add_action('wp_nav_menu_item_custom_fields', 'laniakea_menu_item_iubenda', 10, 2);


function laniakea_save_menu_item_iubenda($menu_id, $menu_item_db_id)
{

    if (isset($_POST['_menu_item_iubenda'][$menu_item_db_id])) {
        update_post_meta($menu_item_db_id, '_menu_item_iubenda', $_POST['_menu_item_iubenda'][$menu_item_db_id]);
    } else {
        delete_post_meta($menu_item_db_id, '_menu_item_iubenda');
    }
}
add_action('wp_update_nav_menu_item', 'laniakea_save_menu_item_iubenda', 10, 2);


function laniakea_add_specific_menu_atts($atts, $item, $args)
{

    $menu_item_iubenda = get_post_meta($item->ID, '_menu_item_iubenda', true);
    if ($menu_item_iubenda == 1) {
        $atts['class'] = 'iubenda-nostyle no-brand iubenda-noiframe iubenda-embed iubenda-noiframe';
    }


    return $atts;
}
add_filter('nav_menu_link_attributes', 'laniakea_add_specific_menu_atts', 10, 3);