Created
November 16, 2018 12:10
-
-
Save aliboy08/9d781132d321c19bdcde7dbc8038b8da to your computer and use it in GitHub Desktop.
Woocoommerce modify product price
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Add to cart markup - added custom input field for event_id | |
$price = get_post_meta(get_the_ID(), 'price', true ); | |
if( $price ) { | |
echo '<form class="cart" action="" method="post" enctype="multipart/form-data"> | |
<div class="quantity"> | |
<label class="screen-reader-text" for="quantity_5beeab967f651">Quantity</label> | |
<input type="number" id="quantity_5beeab967f651" class="input-text qty text" step="1" min="1" max="" name="quantity" value="1" title="Qty" size="4" pattern="[0-9]*" inputmode="numeric" aria-labelledby=""> | |
</div> | |
<input type="hidden" name="event_id" value="'. get_the_ID() .'"> | |
<button type="submit" name="add-to-cart" value="119" class="single_add_to_cart_button button alt">Add to cart</button> | |
</form>'; | |
} | |
// On add to cart | |
function add_cart_item_data( $cart_item_data, $product_id, $variation_id ) { | |
if( isset($_POST['event_id']) ){ | |
// add event id price to data | |
$cart_item_data['event_price'] = get_post_meta((int)$_POST['event_id'], 'price', true); | |
} | |
return $cart_item_data; | |
} | |
add_filter( 'woocommerce_add_cart_item_data', 'add_cart_item_data', 10, 3 ); | |
// Apply added data price | |
function before_calculate_totals( $cart_obj ) { | |
if ( is_admin() && ! defined( 'DOING_AJAX' ) ) { | |
return; | |
} | |
// Iterate through each cart item | |
foreach( $cart_obj->get_cart() as $key=>$value ) { | |
if( isset( $value['event_price'] ) ) { | |
$price = $value['event_price']; | |
$value['data']->set_price( ( $price ) ); | |
} | |
} | |
} | |
add_action( 'woocommerce_before_calculate_totals', 'before_calculate_totals', 10, 1 ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment