skip to Main Content
function wooprice(){
    global $product;
    // 1 Get product varations
    $product_variations = $product->get_available_variations();

    // 2 Get one variation id of a product
    $variation_product_id = $product_variations [0]['variation_id'];

    // 3 Create the product object
    $variation_product = new WC_Product_Variation( $variation_product_id );

    if ($product->is_type( 'variable' )) :
          if( $variation_product ->sale_price !=0 ) :
            echo $variation_product ->sale_price;

          else :
            echo $variation_product ->regular_price;
          endif;

    else :
      echo wc_price($product->get_price());
    endif;

}

I am using this function in price.php in my theme.
enter image description here

This works well if the products are variable products, but fails when the product is simple.

It throws a fatal error if the product is simple:

Fatal error: Uncaught Error: Call to undefined method WC_Product_Simple::get_available_variations() in /home3/

I think this needs to be corrected:

else :
 echo wc_price($product->get_price());

2

Answers


  1. You need to move your step 1, 2 and 3 inside the if block

    function wooprice(){
        global $product;
        if ($product->is_type( 'variable' )) :
              // 1 Get product varations
             $product_variations = $product->get_available_variations();
    
             // 2 Get one variation id of a product
             $variation_product_id = $product_variations [0]['variation_id'];
    
             // 3 Create the product object
             $variation_product = new WC_Product_Variation( $variation_product_id );
    
    
              if( $variation_product ->sale_price !=0 ) :
                echo $variation_product ->sale_price;
    
              else :
                echo $variation_product ->regular_price;
              endif;
    
        else :
          echo wc_price($product->get_price());
        endif;
    
    }
    
    Login or Signup to reply.
  2. function wooprice() {
    
        global $product;
    
    
        if ($product->is_type('variable')) :
    
            // 1 Get product varations
            $product_variations = $product->get_available_variations();
    
            // 2 Get one variation id of a product
            $variation_product_id = $product_variations [0]['variation_id'];
    
            // 3 Create the product object
            $variation_product = new WC_Product_Variation($variation_product_id);
    
            if ($variation_product->sale_price != 0) :
                echo $variation_product->sale_price;
    
            else :
                echo $variation_product->regular_price;
            endif;
    
        else :
            echo $product->get_price();
        endif;
    }
    

    Try this, I have made some modifications to your code

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