i am trying to get the custom fields with this function and multiply by the product price. I am getting the product price but when printing the custom fields, i am only getting zeros.. i dont understand why, i had tryed get_metadata()
and get_post_custom()
too.. but nothing works
function filter_woocommerce_cart_product_subtotal( $product_subtotal, $product, $quantity, $instance ) {
$fields = get_post_meta(get_the_id(), false);
$add_on = $product->get_price()*$fields[0] + $product->get_price()*$fields[1] + $product-
>get_price()*0.75*$fields[2];
return $product_subtotal + $add_on;
};
add_filter( 'woocommerce_cart_product_subtotal', 'filter_woocommerce_cart_product_subtotal', 10, 4 );
I have tryed to get single fields too but always getting zeros.
I can get the custom fields in function below and save it in a global variable but when i try to access the global variable in the function above, i get zero again.
function tour_product_add_on_cart_item_data( $cart_item, $product_id, $cart ){
/*
if( isset( $_POST['time_add_on'] ) ) {
$cart_item['time_add_on'] = sanitize_text_field( $_POST['time_add_on'] );
}
*/
if( isset( $_POST['date_add_on'] ) ) {
$cart_item['date_add_on'] = sanitize_text_field( $_POST['date_add_on'] );
}
if( isset( $_POST['place_add_on'] ) ) {
$cart_item['place_add_on'] = sanitize_text_field( $_POST['place_add_on'] );
}
if( isset( $_POST['adult_add_on'] ) ) {
$cart_item['adult_add_on'] = sanitize_text_field( $_POST['adult_add_on'] );
}
if( isset( $_POST['child_add_on'] ) ) {
$cart_item['child_add_on'] = sanitize_text_field( $_POST['child_add_on'] );
}
if( isset( $_POST['infant_add_on'] ) ) {
$cart_item['infant_add_on'] = sanitize_text_field( $_POST['infant_add_on'] );
}
$product = wc_get_product($product_id);
$GLOBALS["fee"] = $_POST['adult_add_on']*$product->get_price() +
$_POST['child_add_on']*$product->get_price() + $_POST['infant_add_on']*0.75*$product->get_price();
return $cart_item;
}
2
Answers
So, i have resolved this issue. When you add a custom field to a woocommerce product or a wordpress post, you have to update it's meta data. Here is a good tutorial of every step you have to follow to add a custom field.
HOW TO ADD WOOCOMMERCE CUSTOM FIELDS TO A PRODUCT
get_post_meta()
second parameter is the meta key value. So you should use for example$date_add_on = get_post_meta(get_the_id(), 'date_add_on')