Search code examples
wordpresswoocommercemultisite

Any way to Overwrite get_stock_quantity in my functions.php?


I am working in Wordpress Multisite and trying to ensure that all the stock info is fetched from the base site tables. I am trying to overwrite get_stock_quantity() woocomerce function in my theme's functions.php. What i found was

public function get_stock_quantity( $context = 'view' ) {
    return $this->get_prop( 'stock_quantity', $context );
}

Now this is neither a filter nor an action. I overwrote one filter that is

add_filter( 'woocommerce_product_get_stock_quantity', 'wcs_custom_get_stock_quantity', 1, 2);

function wcs_custom_get_stock_quantity( $availability, $_product ) {
    global $wpdb;
    $productQuantity = $wpdb->get_results( 'SELECT * FROM '.$wpdb->base_prefix.'postmeta WHERE post_id = '.$_product->get_id() ." AND meta_key = '_stock'", OBJECT );
    return $productQuantity[0]->meta_value;
}

But woocommerce_product_get_stock_quantity only works on the Products List page. The individual product-edit page uses get_stock_quantity.

How can I overwrite it without changing Core files? Thanks


Solution

  • The correct way to alter get_stock_quantity() method depends on the product. AS you have already notice looking at the source code you see that:

    return $this->get_prop( 'stock_quantity', $context );
    

    Now get_prop() method is a part of WC_Data class and has a generic filter hook:

    $value = apply_filters( $this->get_hook_prefix() . $prop, $value, $this );
    

    And if you look to get_hook_prefix() method you have this:

    return 'woocommerce_' . $this->object_type . '_get_';
    

    For product variations the object_type is: product_variation
    For other products the object_type is: product
    The $prop argument is stock_quantity

    So know you can built the related filter hooks. Try this:

    add_filter( 'woocommerce_product_get_stock_quantity' ,'custom_get_stock_quantity', 10, 2 );
    add_filter( 'woocommerce_product_variation_get_stock_quantity' ,'custom_get_stock_quantity', 10, 2 );
    function custom_get_stock_quantity( $value, $product ) {
        $value = 15; // <== Just for testing
        return $value;
    }
    

    So for product variations you use woocommerce_product_variation_get_stock_quantity filter hook.
    And for the other cases woocommerce_product_get_stock_quantity filter hook