wordpresswoocommerceoverridingcart

Woocommerce connecting From price.php to functions.php


How do I retrieve select input from price.php to functions.php?

Here is my price.php code, (hresults is taken from the database):

<select class="form-control" id="hotel" name="hotel">
    <?php

        foreach ( $hresults as $hresult ) { 
            echo "<option>" . $hresult->hotel . " + ₱" . $hresult->hotelprice . "</option>";
        }
    ?>
</select>

Here is the functions.php code:

function add_custom_price( $cart_object ) {

    $pricesplit = explode("$",$_POST['hotel']);
    $hotelprice = (int) $pricesplit;
    foreach ( $cart_object->cart_contents as $key => $value ) { 

      $quantity = floatval( $value['quantity'] );
      $orgPrice = floatval( $value['data']->price );
      $value['data']->price = ( ( $orgPrice + $hotelprice ) * $quantity );

    }

}

add_action( 'woocommerce_before_calculate_totals', 'add_custom_price' );

My question is, how do I retrieve the hotel select input and use it for calculations overriding the woocommerce price?

enter image description here

First the user selects the hotel and airfare, which has a price on their side. Then, then once the user adds it to the cart, it overrides the price. Depending on the chosen hotel and airport.

For example:


Solution

  • Markup in your price.php is not correct. The "options" in select field are missing their respective values. That is why you are not getting the price value from the select field. Code in your price.php should be as follows.

    <select class="form-control" id="hotel" name="hotel">
        <?php
            foreach ( $hresults as $hresult ) { 
                echo '<option value="<?php echo($hresult->hotelprice); ?>">' . $hresult->hotel . ' + ₱' . $hresult->hotelprice . '</option>';
            }
        ?>
    </select>
    

    I hope this will solve your problem. Note the change in use of double quotes (") and single quote (').