Click here to Skip to main content
15,886,919 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm using woocommerce on my Wordpress. I created a code that I'll show you below. I put it inside function.php and a js called custom-fields.js. As you can see in this image[^], each customer with email has different prices so the customer will have 3 euros of personalized price while the customer will have 2, 4 euros of personalized price. This all works when I press the Update button. But when I refresh the page, obviously the input boxes become empty, I would like the input boxes to remain completed so that next time I can check and change the prices. (I don't want to save them locally) Can you help me?

I'll show you my code below, I put it inside function.php and a js called custom-fields.js. As you can see in the image of the link that I attach here [^].
Each customer with email has different prices so the customer will have 3 euros of personalized price while the customer will have 2, 4 euros of personalized price. This all works when I press the Update button. But when I refresh the page, obviously the input boxes become empty. I would like the input boxes to remain completed so that next time I can check and change the prices. (I don't want to save them locally) Can you help me?

PHP:
PHP
// Aggiungi una scheda personalizzata nella pagina del prodotto
add_filter('woocommerce_product_data_tabs', 'custom_product_data_tab');
function custom_product_data_tab($tabs) {
    $tabs['custom_tab'] = array(
        'label' => 'Personalizza Prezzo',
        'target' => 'custom_tab_content',
        'class' => array(),
    );
    return $tabs;
}

// Carica il tuo script JavaScript
function enqueue_custom_fields_script() {
    wp_enqueue_script('custom-fields', get_template_directory_uri() . '/custom-fields.js', array('jquery'), '1.0', true);
}
add_action('admin_enqueue_scripts', 'enqueue_custom_fields_script');

// Contenuto della scheda personalizzata
add_action('woocommerce_product_data_panels', 'custom_product_data_fields');
function custom_product_data_fields() {
    global $post;

    echo '<div id="custom_tab_content" class="panel woocommerce_options_panel">';
    echo '<div class="options_group">';

    // Bottone per aggiungere campi personalizzati
    echo '<div id="custom-fields-container">';
    echo '<button id="add-custom-field" class="button">Aggiungi</button>';
    echo '</div>';

    // Contenitore per le input box aggiunte dinamicamente
    echo '<div id="custom-fields"></div>';

    echo '</div>';
    echo '</div>';
}

// Aggiungi l'azione per salvare i dati personalizzati quando si aggiorna il prodotto
add_action('woocommerce_process_product_meta', 'save_custom_product_data');
function save_custom_product_data($post_id) {
    // Salva le email dei clienti
    $custom_emails = isset($_POST['_custom_email']) ? array_map('sanitize_text_field', $_POST['_custom_email']) : array();
    update_post_meta($post_id, '_custom_email', $custom_emails);

    // Salva i prezzi personalizzati corrispondenti alle email
    $custom_prices = isset($_POST['_custom_price']) ? array_map('sanitize_text_field', $_POST['_custom_price']) : array();

    // Assicurati che ci siano corrispondenze tra le email e i prezzi personalizzati
    if (count($custom_emails) === count($custom_prices)) {
        $email_price_mapping = array();

        for ($i = 0; $i < count($custom_emails); $i++) {
            $email = $custom_emails[$i];
            $price = $custom_prices[$i];

            // Se l'email e il prezzo sono validi, li associa
            if (!empty($email) && !empty($price)) {
                $email_price_mapping[$email] = $price;
            }
        }

        update_post_meta($post_id, '_custom_email_price_mapping', $email_price_mapping);
    }
}

// Sostituisci il prezzo di listino con il prezzo personalizzato
add_filter('woocommerce_get_price', 'replace_list_price', 10, 2);
function replace_list_price($price, $product) {
    $custom_email_price_mapping = get_post_meta($product->get_id(), '_custom_email_price_mapping', true);

    if (!empty($custom_email_price_mapping)) {
        $current_user = wp_get_current_user();
        $user_email = $current_user->user_email;

        if (array_key_exists($user_email, $custom_email_price_mapping)) {
            return $custom_email_price_mapping[$user_email];
        }
    }

    return $price;
}


JS:
JavaScript
jQuery(document).ready(function ($) {
    // Aggiungi un evento click al pulsante "Aggiungi"
    $("#add-custom-field").on("click", function (e) {
        e.preventDefault();

        // Crea un nuovo input box per l'email
        var newInputEmail = $('<input type="text" 
        name="_custom_email[]" placeholder="Inserisci l\'email del cliente">');
        
        // Crea un nuovo input box per il prezzo personalizzato
        var newInputPrice = $('<input type="text" name="_custom_price[]" 
         placeholder="Inserisci il prezzo personalizzato">');

        // Aggiungi i nuovi input box al contenitore dei campi personalizzati
        $("#custom-fields").append(newInputEmail);
        $("#custom-fields").append(newInputPrice);
    });
});


What I have tried:

But when I refresh the page obviously the input boxes become empty, I would like the input boxes to remain completed so that next time, I can check and change the prices. (I don't want to save them locally) Can you help me?
Posted
Updated 3-Nov-23 3:36am
v3

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900