To display products that do not match the filter (“No” products) below the filtered products (“Yes” products), you can modify your query logic to retrieve both filtered and unfiltered products in a single operation. Here’s how to implement it:
Steps:
-
Modify the Query Logic:
- Create two queries: one for filtered products (“Yes”) and another for unfiltered products (“No”).
- Merge the results so that “Yes” products appear first, followed by “No” products.
-
Implementation:
Use custom query parameters and manipulate the results before passing them back to WooCommerce.
Updated Code:
Here’s how your sort_products_by_positive_attributes
function can be updated:
function sort_products_by_positive_attributes($query) {
if (!is_admin() && $query->is_main_query() && is_woocommerce()) {
// Get all products matching the filter (e.g., 'tiled' = 'yes')
$filtered_args = [
'post_type' => 'product',
'posts_per_page' => -1, // Adjust as needed
'meta_query' => [
[
'key' => 'tiled', // Replace 'tiled' with your custom field key
'value' => 'yes',
'compare' => '='
]
]
];
$filtered_query = new WP_Query($filtered_args);
// Get all products NOT matching the filter (e.g., 'tiled' = 'no')
$unfiltered_args = [
'post_type' => 'product',
'posts_per_page' => -1, // Adjust as needed
'meta_query' => [
[
'key' => 'tiled', // Replace 'tiled' with your custom field key
'value' => 'no',
'compare' => '='
]
]
];
$unfiltered_query = new WP_Query($unfiltered_args);
// Combine the results: Filtered products first, then unfiltered
$merged_posts = array_merge($filtered_query->posts, $unfiltered_query->posts);
// Set the query posts and post count
$query->posts = $merged_posts;
$query->post_count = count($merged_posts);
}
}
add_action('pre_get_posts', 'sort_products_by_positive_attributes');
Explanation:
-
Filtered Query:
- Retrieves products where the meta field
tiled
is set toyes
. - Replace
'tiled'
with the actual meta key for your field.
- Retrieves products where the meta field
-
Unfiltered Query:
- Retrieves products where the meta field
tiled
is set tono
.
- Retrieves products where the meta field
-
Merge Results:
- Combines the two sets of posts, placing the filtered products first.
- The merged list is then assigned to
$query->posts
.
-
Pagination Support (Optional):
- If you’re using pagination, you’ll need to handle it manually by slicing
$merged_posts
based onpaged
andposts_per_page
.
- If you’re using pagination, you’ll need to handle it manually by slicing
Debugging Tips:
- Use
error_log(print_r($query->posts, true));
to verify the merged results. - Ensure the custom field
tiled
is correctly assigned to your products in the WooCommerce product meta.
This approach ensures that all products are displayed, with the filtered products at the top and the unfiltered ones below. Let me know if further adjustments are needed!