skip to Main Content

How to change a price when stock is “0”?

I have a “reguler price” and “another price” in the admin side. “another price” is a metadata (you can see in code -> ‘_alg_msrp’).
I trigger with this code :

if($product->stock_quantity == 0 ){
    function return_custom_price($price, $product) {
        global $post, $blog_id;
        $post_id = $post->ID;
        $price = get_post_meta( get_the_ID(), '_alg_msrp', true );

        return $price;
    }
    add_filter('woocommerce_get_price', 'return_custom_price', 10, 2);
}

The price does change but I want it only to change on the front side, not on the admin side. This code change the whole view. I mean, how can it affect only the front page, not the admin page, like in “Products” tab in WooCommerce.
Thanks for any Suggest.

2

Answers


  1. It depend where you want to change, for simple product

    “woocommerce_get_price” is deprecated since version 3.0.0

    Use “woocommerce_product_get_price” instead.

    add_filter('woocommerce_product_get_price', 'new_price', 11, 2 );
    add_filter('woocommerce_product_get_regular_price', 'new_price', 11, 2 );
    function new_price( $price, $product ) {
        if($product && !is_admin()){
          if($product->stock_quantity == 0 ){
           $new_price = get_post_meta( $product->get_id(), '_alg_msrp', true );
           if($new_price){
            return $new_price;
           }
          }
        }
        return $price;
    }
    
    Login or Signup to reply.
  2. I would change it so the logic is inside the function:

    function return_custom_price($price, $product) {
        if ( is_admin() || $product->stock_quantity != 0 ) 
            return $price;
    
        $custom_price = get_post_meta( $product->get_id(), '_alg_msrp', true );
        return ($custom_price == '') ? $price : $custom_price;
    }
    add_filter('woocommerce_get_price', 'return_custom_price', 10, 2);
    

    This will return custom price only if it’s not empty. Otherwise it will return the regular price.

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