Display only when price is over 10$ on the WooCommerce single product page

Viewed 168

I use this code to show the customer what it costs over several months if the customer wants to pay off several installments.

But the code should only work on items above $ 10 and be inactive for items below.

Anyone have any suggestions?

add_action( 'woocommerce_single_product_summary', 'show_emi', 1 );
function show_emi() {
       global $product; 
       $id = $product->get_id();
        $product = wc_get_product( $id );
        $a=$product->get_price();
        $b  = 20;
        $c = 100;
        $d = $a / $b;
        $total = $a / $b;
      echo '<div class="afbetaling">
    <b>  Eller kun '.$total.' kr./md i 20 mdr. </b>
0% i rente og gebyrer. <br> Få mere info i butikken</div>';
}
1 Answers

Your code contains some minor mistakes or use some optimization

  • You use global $product; to then get the product ID of this object, and then you use that product id to obtain the product object. An unnecessary step, since you already have access to the $product
  • Use clear variables that tell something against $a, $b and $c
  • Using the __( string $text, string $domain = 'default' ) function allows to make the text translatable
  • To meet your demand, you have to put the product price in an if condition, and only continue if this condition is met

So you get:

function action_woocommerce_single_product_summary() {
    // Get the global product object
    global $product;
    
    // Is a WC product
    if ( is_a( $product, 'WC_Product' ) ) {
        // Get price
        $price = $product->get_price();
        
        // Above 10
        if ( $price > 10 ) {
            // Settings
            $months = 20;
            $total = $price / $months;
            
            // Message
            $message = sprintf( __( '<strong>Or only DKK %s / month for %s months</strong>, 0%% in interest and fees. Get more info in the store', 'woocommerce' ), $total, $months );
            
            // Output
            echo '<div class="afbetaling">' . $message . '</div>';
        }
    }
}
add_action( 'woocommerce_single_product_summary', 'action_woocommerce_single_product_summary', 10, 0 );
Related