S
S
sasha7612019-06-10 18:49:05
WordPress
sasha761, 2019-06-10 18:49:05

Where did I go wrong in this code?

Good afternoon, the Query monitor plugin suggests that this functionality (code) causes php errors.
This code is needed in order to display the discount percentage in variable products

add_filter('woocommerce_variable_price_html', 'mycustom_variation_price2', 10, 2 );

function mycustom_variation_price2( $price, $product ) {
#Step 1: Get product varations

$available_variations = $product->get_available_variations();

#Step 2: Get product variation id
$variation_id=$available_variations[0]['variation_id']; // Getting the variable id of just the 1st product. You can loop $available_variations to get info about each variation.

#Step 3: Create the variable product object
$variable_product1= new WC_Product_Variation( $variation_id );

#Step 4: You have the data. Have fun :)
$regular_price = $variable_product1 ->regular_price;
$sales_price = $variable_product1 ->sale_price;

$percentage = round( ( ( $regular_price - $sales_price ) / $regular_price ) * 100 );

return $price .'<div class="sale">'. sprintf( __(' Sale %s', 'woocommerce' ), $percentage . '%' ).'</div>';
}

But what errors it writes,
5cfe7b87ae149370947912.png
I think maybe I’m referring to the wrong filter ....

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
sasha761, 2019-06-10
@sasha761

I think to solve this error, you need to display this code if there is a discount in the variable product, but I don’t know which function to call
something like if (variable_product_have_sale) {....
solved this issue. The code is not optimized but still...
Here is the code:

add_filter('woocommerce_variable_price_html', 'mycustom_variation_price2', 10, 2 );

function mycustom_variation_price2( $price, $product ) {
  if ( ! is_admin() && ((is_shop() || is_product_category() || is_archive()))) {
    
#Step 1: Get product varations

$available_variations = $product->get_available_variations();

#Step 2: Get product variation id
$variation_id=$available_variations[0]['variation_id']; // Getting the variable id of just the 1st product. You can loop $available_variations to get info about each variation.

#Step 3: Create the variable product object
$variable_product1= new WC_Product_Variation( $variation_id );

#Step 4: You have the data. Have fun :)
$regular_price = $variable_product1 ->regular_price;
$sales_price = $variable_product1 ->sale_price;

    if ( $product->is_on_sale() ) {
$percentage = round( ( ( $regular_price - $sales_price ) / $regular_price ) * 100 );
       return $price .'<div class="sale">'. sprintf( __(' Sale %s', 'woocommerce' ), $percentage . '%' ).'</div>';
    }
    else {
    return $price ;	
    }
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question