How would I get my “woocommerce_product_is_visible” filter hook to work with a WordPress custom query.

If I change “woocommerce_product_is_visible” to “pre_get_posts” I get “Warning: Missing argument 2”.

So my question is how to make the filter work with WordPress custom query, if it’s not possible how do I fix the error that occurs when using “pre_get_posts” instead of “woocommerce_product_is_visible” so it applies to all custom query?

$args = array(
    'posts_per_page' => -1,
    'tax_query' => array(
    'relation' => 'AND',
        array(
        'taxonomy' => 'product_cat',
        'field' => 'slug',
        'terms' => $product_category->slug
        )
    ),
    'post_type' => 'product',
    'orderby' => 'title',
    'meta_query' => array(
        array(
            'key' => '_stock_status',
            'value' => 'instock'
        ),
        array(
            'key' => '_backorders',
            'value' => 'no'
        ),
    )
);


function bb_remove_product_stock_region( $is_visible, $product_id) {

    $product_variable = new WC_Product_Variable($product_id);
    $product_variations = $product_variable->get_available_variations();

    foreach ( $product_variations as $variation ) {

        /** Get users region. */
        $user_region = bb_get_user_region();

        /** Get products regions. */
        $product_region = $variation['attributes']['attribute_pa_regions'];
        if ( $user_region === $product_region && ! $variation['is_in_stock'] ) {
            $is_visible = false;
            return $is_visible;
        }
        else if ( $user_region === $product_region && $variation['is_in_stock'] ) {
            $is_visible = true;
            return $is_visible;
        }
    }

}


add_filter(
    'woocommerce_product_is_visible',
    'bb_remove_product_stock_region',
    10,
    2
);

Read more here: Passing a filter to custom query


Solution:

If you know the solution of this issue, please leave us a reply in Comment section, to update the question.


Wordpress related questions and answers: