Search code examples
phpwordpresswoocommercecartsubscription

Adding text before and after prices in WooCommerce excluding subscriptions products


In WooCommerce I use the following code to add some text around the displayed product price ("Rent:" and "/day") like:

function cp_change_product_price_display( $price ) {
    echo 'Rent: ' . $price . '/day';    
}
add_filter( 'woocommerce_get_price_html', 'cp_change_product_price_display' );
add_filter( 'woocommerce_cart_item_price', 'cp_change_product_price_display' );

I also use the plugin "YITH WooCommerce Subscription" and there is a problem with my code. Now in the subscription packages I have one of this price displays:

  • Rent: $20/7 days/day
  • Rent: $80/month/day.

How to exclude subscription products or category of subscriptions from my codeTo avoid this problems?


Solution

  • You can add condition to check if current product is subscription or not. Example.

    function cp_change_product_price_display( $price, $instance ) {
        if ( 'yes' === $instance->get_meta( '_ywsbs_subscription' ) ) {
            return $price;
        }
        return 'Rent: ' . $price . '/day';
    }
    
    add_filter( 'woocommerce_get_price_html', 'cp_change_product_price_display', 10, 2 );
    

    And for cart price:

    function cp_change_product_price_display_in_cart( $price, $cart_item, $cart_item_key ) {
        $product = $cart_item['data'];
        if ( 'yes' === $product->get_meta( '_ywsbs_subscription' ) ) {
            return $price;
        }
        return 'Rent: ' . $price . '/day';
    }
    
    add_filter( 'woocommerce_cart_item_price', 'cp_change_product_price_display_in_cart', 10, 3 );