skip to Main Content

I’ve a problem. I want to execute function after two checkboxes are checked. I’ve tried everything but nothing works. (This should replace price in Woocommerce)

My PHP function:

    jQuery(function($) {
        var cb = 'input[name="extra1_option"]'
            cb1 = 'input[name="extra2_option"]'
            cb2 = 'input[name="extra1_option"], input[name="extra2_option"]'
            pp = 'price';

        // On change / select a variation

        $(cb2).on( 'change', function(){
            if( $(cb).prop('checked') === true){
                $(pp).html('<?php echo $disp_price_sum_p_html; ?>');
                
            }
            else if( $(cb1).prop('checked') === true){
                $(pp).html('<?php echo $disp_price_sum_n_html; ?>');
            }
            else if( ($(cb).is(':checked') === true) && ($(cb1).prop('checked') === true)){ // I've tried everythiing here
                $(pp).html('<?php echo $disp_price_sum_pn_html; ?>');
            }
            else
                $(pp).html('<?php echo $active_price_html; ?>');
        })

    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<?php
    $active_price = 100;
    $extra_price1 = 2;
    $extra_price2 = 3;
    $extra_price1_html   = 2;
    $extra_price2_html   = 3;
    $active_price_html   = 100;
    $disp_price_sum_n_html = $active_price + $extra_price1;
    $disp_price_sum_n_html = $active_price + $extra_price2;
    $disp_price_sum_pn_html = $active_price + $extra_price1 + $extra_price2;

      echo '<div class="hidden-field">
    <p class="form-row form-row-wide" id="extra1_option_field" data-priority="">
    <label class="checkbox"> 'Extra Field 1: .
    ' <input type="checkbox" class="input-checkbox " name="extra1_option" id="extra1_option" value="extra1"> + ' . $extra_price1_html .'</label></span></p>
    <input type="hidden" name="extra_price1" value="' . $extra_price1 . '">
    <p class="form-row form-row-wide" id="extra2_option_field" data-priority="">
    <label class="checkbox"> 'Extra Field 2: .
    ' <input type="checkbox" class="input-checkbox " name="extra2_option" id="extra2_option" value="extra2"> + ' . $extra_price2_html .
    '</label></span></p>
    
    <input type="hidden" name="extra_price1" value="' . $extra_price1 . '">
    <input type="hidden" name="extra_price2" value="' . $extra_price2 . '">
    <input type="hidden" name="active_price" value="' . $active_price . '">
    <p>Price: + ' . $price .'
    </div>';
    

    ?>
function product_option_custom_field(){
    global $product;

    $active_price = (float) $product->get_price();
    $extra_price1 = (float) $product->get_meta( '_extra_field1' );
    $extra_price2 = (float) $product->get_meta( '_extra_field2' );
    $extra_price1_html   = strip_tags( wc_price( wc_get_price_to_display( $product, array('price' => $extra_price1 ) ) ) );
    $extra_price2_html   = strip_tags( wc_price( wc_get_price_to_display( $product, array('price' => $extra_price2 ) ) ) );
    $active_price_html   = wc_price( wc_get_price_to_display( $product ) );
    $disp_price_sum_p_html = wc_price( wc_get_price_to_display( $product, array('price' => $active_price + $extra_price1) ) );
    $disp_price_sum_n_html = wc_price( wc_get_price_to_display( $product, array('price' => $active_price + $extra_price2) ) );
    $disp_price_sum_pn_html = wc_price( wc_get_price_to_display( $product, array('price' => $active_price + $extra_price1 + $extra_price2) ) );

    echo '<div class="hidden-field">
    <p class="form-row form-row-wide" id="extra1_option_field" data-priority="">
    <span class="woocommerce-input-wrapper"><label class="checkbox"> ' . __("Extra Field 1:", "Woocommerce") .
    ' <input type="checkbox" class="input-checkbox " name="extra1_option" id="extra1_option" value="1"> + ' . $extra_price1_html .
    '</label></span></p>
    <input type="hidden" name="extra_price2" value="' . $extra_price2 . '">
    <p class="form-row form-row-wide" id="extra2_option_field" data-priority="">
    <span class="woocommerce-input-wrapper"><label class="checkbox"> ' . __("Extra field 2:", "Woocommerce") .
    ' <input type="checkbox" class="input-checkbox " name="extra2_option" id="extra2_option" value="1"> + ' . $extra_price2_html .
    '</label></span></p>
    <input type="hidden" name="extra_price2" value="' . $extra_price2 . '">
    <input type="hidden" name="active_price" value="' . $active_price . '"></div>';

My Jquery:

<script type="text/javascript">
    jQuery(function($) {
        var cb = 'input[name="extra1_option"]'
            cb1 = 'input[name="extra2_option"]'
            cb2 = 'input[name="extra1_option"], input[name="extra2_option"]'
            pp = 'p.price';

        // On change / select a variation

        $(cb2).on( 'change', function(){
            if( $(cb).prop('checked') === true){
                $(pp).html('<?php echo $disp_price_sum_p_html; ?>');
                
            }
            else if( $(cb1).prop('checked') === true){
                $(pp).html('<?php echo $disp_price_sum_n_html; ?>');
            }
            else if( ($(cb).is(':checked') === true) && ($(cb1).prop('checked') === true)){ // I've tried everythiing here
                $(pp).html('<?php echo $disp_price_sum_pn_html; ?>');
            }
            else
                $(pp).html('<?php echo $active_price_html; ?>');
        })

    });


    </script>

I’ve also tried to make two functions, Is any one available to help me?

I’ve tried to remake statements and add another function

EDITED:

Sorry,I’m tring all the time run this but still can’t even invoke this to test:

  const updatePrice = () => {
    var extra1Checked = $('input[name="extra1_option"]').is(':checked');
    var extra2Checked = $('input[name="extra2_option"]').is(':checked');

    // Determine the correct price HTML to display
    if (extra1Checked && extra2Checked) alert("a");
    else if (extra1Checked)             alert("a1");
    else if (extra2Checked)            alert("a2");
    // Update the price paragraph
    $priceParagraph.html($priceParagraph.data(priceData));
  }

  $('div.hidden-field input.input-checkbox').on('change', updatePrice);
  // Call updatePrice on script load to set the initial price state
  updatePrice();
});

2

Answers


  1. Please note you have TWO hidden name="extra_price2"

    You can do this to make it more DRY and readable

    <p class="<?php echo esc_attr( apply_filters( 'woocommerce_product_price_class', 'price' ) ); ?>"
       data-sum-p-html="<?php echo htmlspecialchars($disp_price_sum_p_html); ?>"
       data-sum-n-html="<?php echo htmlspecialchars($disp_price_sum_n_html); ?>"
       data-sum-pn-html="<?php echo htmlspecialchars($disp_price_sum_pn_html); ?>"
       data-active-html="<?php echo htmlspecialchars($active_price_html); ?>">
        <?php echo $product->get_price_html(); ?>
    </p>
    
    $(function() {
      const $priceParagraph = $('p.price'); // Cache the price paragraph
    
      const updatePrice = () => {
        var extra1Checked = $('input[name="extra1_option"]').is(':checked');
        var extra2Checked = $('input[name="extra2_option"]').is(':checked');
    
        // Determine the correct price HTML to display
        let priceData = 'active-html'; // default
        if (extra1Checked && extra2Checked) priceData = 'sum-pn-html';
        else if (extra1Checked)             priceData = 'sum-p-html';
        else if (extra2Checked)             priceData = 'sum-n-html';
        // Update the price paragraph
        $priceParagraph.html($priceParagraph.data(priceData));
      }
    
      $('div.hiddenField input.input-checkbox').on('change', updatePrice);
      // Call updatePrice on script load to set the initial price state
      updatePrice();
    });
    
    Login or Signup to reply.
  2. The following will, when selecting any extra options:

    • change the product displayed price on single product pages
    • change the cart item price on cart, mini cart and checkout pages,
    • Display the selected options on cart items.

    The complete code (based on your product custom setting fields):

    add_action('woocommerce_before_add_to_cart_button', 'single_product_checkboxes_options');
    function single_product_checkboxes_options(){
        global $product;
    
        $active_price = wc_get_price_to_display( $product );
        $html = '';
        
        if( $extra_field1 = $product->get_meta('_extra_field1') ) {
            $extra_price1 = wc_get_price_to_display( $product, array(
                'price' =>  $extra_field1 ) );
    
            $html .= '<p class="form-row form-row-wide" id="extra1_option_field" data-priority="">
            <span class="woocommerce-input-wrapper"><label class="checkbox"> ' . __("Extra Field 1", "Woocommerce") .
            '&nbsp;<input type="checkbox" class="input-checkbox " name="extra1_option" id="extra1_option" value="1"> + ' . wc_price($extra_price1) .
            '</label></span></p>';
        }
    
        if( $extra_field2 = $product->get_meta('_extra_field2') ) {
            $extra_price2 = wc_get_price_to_display( $product, array(
                'price' =>  $extra_field2 ) );
        
            $html .= '<p class="form-row form-row-wide" id="extra2_option_field" data-priority="">
            <span class="woocommerce-input-wrapper"><label class="checkbox"> ' . __("Extra field 2", "Woocommerce") .
            '&nbsp;<input type="checkbox" class="input-checkbox " name="extra2_option" id="extra2_option" value="1"> + ' . wc_price($extra_price2) .
            '</label></span></p>';
        }
    
        if ( $extra_field1 || $extra_field2 ) {
            $html .= '<div class="calculated-prices" style="display:none;">';
            $html .= $extra_field1 ? '<div class="sum_price_op1">'.wc_price($active_price + $extra_price1).'</div>' : '';
            $html .= $extra_field2 ? '<div class="sum_price_op2">'.wc_price($active_price + $extra_price2).'</div>' : '';
            $html .= $extra_field1 && $extra_field2 ? '<div class="sum_price_op_both">' .
                wc_price($active_price + $extra_price1 + $extra_price2) . '</div>' : '';
            $html .= '</div>';
    
            echo '<div class="custom-fields">' . $html . '</div>';
        }
    }
    
    add_action('woocommerce_after_add_to_cart_form', 'single_product_checkboxes_options_js');
    function single_product_checkboxes_options_js(){
        ?>
        <script>
        jQuery(function($) {
            const initialPrice = $('p.price').html();
            var cbChecked1 = cbChecked2 = false;
    
            $('form.cart').on('change', 'input#extra1_option, input#extra2_option', function(){
                if ( $(this).attr('name') === 'extra1_option' ) {
                    cbChecked1 =  $(this).prop('checked');
                } else {
                    cbChecked2 = $(this).prop('checked');
                }
    
                if ( cbChecked1 && !cbChecked2 ) {
                    $('p.price').html($('div.sum_price_op1').html());
                } else if ( !cbChecked1 && cbChecked2 ) {
                    $('p.price').html($('div.sum_price_op2').html());
                } else if ( cbChecked1 && cbChecked2 ) {
                    $('p.price').html($('div.sum_price_op_both').html());
                } else {
                    $('p.price').html(initialPrice);
                }
            });
        });
        </script>
        <?php
    }
    
    // Save custom fields as custom cart item data
    add_filter('woocommerce_add_cart_item_data', 'add_custom_cart_item_data', 20, 2 );
    function add_custom_cart_item_data( $cart_item_data, $product_id ) {
        $product = wc_get_product($product_id);
    
        if ( isset($_POST['extra1_option']) ) {
            $cart_item_data['extra_options']['1'] = $product->get_meta('_extra_field1');
        }
        if ( isset($_POST['extra2_option']) ) {
            $cart_item_data['extra_options']['2'] = $product->get_meta('_extra_field2');
        } 
        return $cart_item_data;
    }
    
    // Display custom fields in Cart and Checkout
    add_filter( 'woocommerce_get_item_data', 'display_custom_cart_item_data', 20, 2 );
    function display_custom_cart_item_data( $cart_data, $cart_item ) {
        if( ! isset($cart_item['extra_options']) ) 
            return $cart_data;
    
        foreach ( $cart_item['extra_options'] as $key => $raw_price ) {
            $cart_data[] = array(
                'key'   => __('Extra option').' '.$key,
                'value' => wc_price( wc_get_price_to_display( $cart_item['data'], array( 'price' => $raw_price ) ) ),
            );
        }
        return $cart_data;
    }
    
    // Cart and mini cart displayed calculated price
    add_filter( 'woocommerce_cart_item_price', 'display_cart_item_price_html', 20, 2 );
    function display_cart_item_price_html( $price_html, $cart_item ) {
        if( ! isset($cart_item['extra_options']) ) 
            return $price_html;
    
        $product = wc_get_product($cart_item['variation_id'] > 0 ? : $cart_item['product_id']);
    
        if ( WC()->cart->display_prices_including_tax() ) {
            $price = wc_get_price_including_tax($product);
        } else {
            $price = wc_get_price_excluding_tax($product);
        }
    
        foreach ( $cart_item['extra_options'] as $key => $raw_price ) {
            if ( WC()->cart->display_prices_including_tax() ) {
                $price += wc_get_price_including_tax( $cart_item['data'], array( 'price' => $raw_price ) );
            } else {
                $price += wc_get_price_excluding_tax( $cart_item['data'], array( 'price' => $raw_price ) );
            }
        }
        return wc_price( $price );
    }
    
    // Change and set cart item custom calculated price
    add_action('woocommerce_before_calculate_totals', 'set_custom_cart_item_price');
    function set_custom_cart_item_price( $cart ) {
        if ( is_admin() && !defined('DOING_AJAX') )
            return;
    
        foreach ( $cart->get_cart() as $item ) {
            if( isset($item['extra_options']) ) {
                $price = $item['data']->get_price();
    
                foreach ( $item['extra_options'] as $key => $raw_price ) {
                    $price += $raw_price;
                }
                $item['data']->set_price($price);
            }
        }
    }
    

    Code goes in functions.php file of your child theme (or in a plugin). Tested and works.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search