add to cart price woocommerce code example

Example 1: add_to_cart how to call it woocommerce

add_action( 'template_redirect', 'quadlayers_add_to_cart_function' );

function quadlayers_add_to_cart_function () {

    $product_id = 1326;

    if ( WC()->cart->get_cart_contents_count() == 0 ) {

        WC()->cart->add_to_cart( $product_id );

    }

}

Example 2: woocommerce update cart 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['csCost'] ) ) {
    $getPrice = $value['data']->get_price();
     $price = $value['csCost'] + $getPrice;
     $value['data']->set_price( ( $price ) );
   }
   if( isset( $value['setCost'] ) ) {
    $getPrice = $value['data']->get_price();
     $price = $value['setCost'] + $getPrice;
     $value['data']->set_price( ( $price ) );
   }
  
 }
}
add_action( 'woocommerce_before_calculate_totals', 'before_calculate_totals', 10, 1 );

Tags:

Misc Example