Search code examples
wordpresswoocommercepost-meta

woocommerce POS pos only meta_query not working with display shop page as categories


I am trying to remove items from my shop that either have 0 stock or are marked to be POS only but for some reason only the 0 stock part works.

Here is my code. What am I doing wrong?

/****
Functions to remove items from store that have 0 stock
*****/
add_action( 'pre_get_posts', 'custom_pre_get_posts_query' );

function custom_pre_get_posts_query( $q ) {
    if ( ! $q->is_main_query() ) return;
    if ( ! $q->is_post_type_archive() ) return;
    if ( ! is_admin() ) {
        $meta_query = $q->get( 'meta_query' );
        $meta_query[] = array(
            'key'       => '_pos_visibility',
            'value'     => 'pos_only',
            'compare'   => '!='
            );
        $meta_query[] = array(
            'key'       => '_stock_status',
            'value'     => 'outofstock',
            'compare'   => '!='
            );

        $q->set( 'meta_query', $meta_query);
    }
    $q->set('orderby', array('date' => 'DESC'));

    remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );

}

thanks Leo


Solution

  • OK I figured out a few things.

    1. THis only seems to be a problem when using the WooCommerce->Settings->Products->Display Shop Page Display is not set to products. i.e it is set to either Categories or categories and products.

    Here is the code I used to eventually solve it.

    add_action( 'woocommerce_product_query', 'hss_shop_query', 10 , 2);
    function hss_shop_query( $q, $that )
    {
    // $q->set( 'author', $vendor_id );
        if ( ! is_admin()  ) {
            $meta_query = $q->get( 'meta_query' );
    
            if (!is_array($meta_query)){
                $meta_query = array();
            }
            $bHasPOSVisibility = false;
            $bHasOutOfStock = false;
    
            foreach ($meta_query as $mq) {
                if ($q->key == '_pos_visibility'){
                    $bHasPOSVisibility = true;
                } else if ($q->key == '_stock_status'){
                    $bHasOutOfStock = true;
                }
            }
    
            if (!$bHasPOSVisibility){
                $meta_query[] = array(
                    'key'       => '_pos_visibility',
                    'value'     => 'pos_only',
                    'compare'   => '!='
                    );
            }
            if (!$bHasOutOfStock){
                $meta_query[] = array(
                    'key'       => '_stock_status',
                    'value'     => 'outofstock',
                    'compare'   => '!='
                    );
            }
            $q->set( 'meta_query', $meta_query);
        }
    
    //error_log("Query: ".var_export($q, true));
    }
    

    I do not know if I need to check if it already exists in the query or not but I put it in for future compatibility if they fix this issue.