WP SITES

3086 Coded Tutorials & 288 Plugins

Display Coupon Code Before Specific Products Conditionally

This code enables you to display a coupon code before specific products based on specific conditions using WooCommerce. In this example, the coupon code only displays if :

  • The product price is $75 or greater
  • The product is in the promoted category
  • The coupon code name is 25OFF

Swap out any of these bolded variables to suit you own requirements.

You can also exclude specific product ids from displaying the coupon advertisement.

add_action('woocommerce_before_single_product_summary', 'display_coupon_on_product_page', 25 );
function display_coupon_on_product_page() {

    global $product;
    
    // Set minimum price threshold
    $min_price = 75;
    
    // Set target category slug
    $target_category = 'promoted';
    
    $product_price = floatval($product->get_price());
    $min_price     = floatval($min_price);
    $product_id    = $product->get_id(); // Ensure we pass the product ID
    
    // Product ID to exclude
    $excluded_product_id = 3007;
    
    // Exclude the specific product
    if ($product_id == $excluded_product_id) {
        return;
    }

    if ( $product_price >= $min_price && has_term( $target_category, 'product_cat', $product_id ) ) {   
 
        $coupon_code = '25OFF';
        $c           = new WC_Coupon($coupon_code);
        
        $discount_type   = $c->get_discount_type();
        $discount_amount = $c->get_amount();
        $expiry_date = $c->get_date_expires() ? $c->get_date_expires()->date('d F') : 'No Expiry';
        
        echo '<div style="display: block; margin-left: auto; margin-right: auto; margin-top: 20px; padding: 10px; background: #f7f7f7; border: 1px solid #ddd; text-align: center;">';
        echo '<span>Use coupon <strong>' . esc_html($coupon_code) . '</strong>';
        echo ' <span>Expires: <strong>' . 'Soon' . '</strong></span>';
        echo '</div>';
    }
    
}

Use any single product page hook.

Leave a Reply

New Plugins