• Resolved creativ3y3

    (@creativ3y3)


    I am trying to limit the number of products showing in the shop by looking up an ACF field on the product to see if it has a value of 1 and using pre_get_posts to filter them out. It all works as expected in the shop, however, when it comes to using filters on the shop page (like price or categories), it brings back all products and categories associated with all products (even the ones I’ve filtered out) so if someone then uses those filters, it shows the products I don’t want to see again. Does anyone have any suggestions how I could overcome this issue? My code looks like this so far:
    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() && is_shop() ) {
    
          $hideProducts = array();
        
          $posts = get_posts(array(
            'numberposts' => -1,
            'post_type'   => 'product',
            'meta_query'  => array(
              'relation'    => 'AND',
              array(
                'key'     => 'sell_product_online',
                'value'     => '1',
                'compare'   => '=',
              ),
            ),
          ));
          
          foreach ($posts as $another) {
                  array_push($hideProducts, $another->ID);
              }
          $q->set( 'post__not_in', $hideProducts ); 
        }
    
        remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );
    
      }

    Any help appreciated.

    • This topic was modified 4 years, 8 months ago by creativ3y3.
    • This topic was modified 4 years, 8 months ago by Jan Dembowski. Reason: Moved to Fixing WordPress, this is not an Developing with WordPress topic
Viewing 3 replies - 1 through 3 (of 3 total)
Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Limit product results in WooCommerce shop page’ is closed to new replies.