Hira Singh
Hira Singh

Reputation: 155

Exclude Products from loop using woocommerce

I have to exclude some products in category loop product page using woocommerce. Only that products, have specific value in meta table will be excluded. I have written below code but this is not working for me. Please somebody help me.

add_filter( '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;

     $q->set( 'meta_query', array(array(
                 array(
                     'key' => '_auction_closed',
                      'compare' => 'NOT EXISTS'
                    )
                 )
               )
             );

    remove_filter( 'pre_get_posts', 'custom_pre_get_posts_query' );

}

Upvotes: 2

Views: 1430

Answers (1)

Bhumi Shah
Bhumi Shah

Reputation: 9476

Try following code:

add_filter( '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;

    $meta_query = $q->get('meta_query');
    $meta_query[] = array(
        'key'=>'_auction_closed',
        'compare'=>'NOT EXISTS',
        );
    $q->set('meta_query',$meta_query);

    remove_filter( 'pre_get_posts', 'custom_pre_get_posts_query' );

}

Upvotes: 1

Related Questions