Skip to content

Instantly share code, notes, and snippets.

@stephenfeather
Created July 3, 2023 23:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stephenfeather/38a13908642f095507ae5424723306b7 to your computer and use it in GitHub Desktop.
Save stephenfeather/38a13908642f095507ae5424723306b7 to your computer and use it in GitHub Desktop.
Modification to allow the filtering of products in PW Bulk Edit based upon the number of categories a product is in. (Wordpress, Woocommerce, Pimwick)
<?php
/**
* Modification to allow the filtering of products in PW Bulk Edit based
* upon the number of categories a product is in.
*
* REF: https://www.pimwick.com/pw-bulk-edit/
*
* @author Stephen Feather
* @copyright Copyright (c) 2023
*/
/**
* Add the 'Category Count' filter type to PW WooCommerce Bulk Edit.
*
* @param array $filter_types Existing filter types.
* @return array Modified filter types.
*/
function pwbe_filter_types_category_count( $filter_types ) {
$filter_types['category_count'] = array( 'name' => 'Category Count', 'type' => 'numeric' );
return $filter_types;
}
add_filter( 'pwbe_filter_types', 'pwbe_filter_types_category_count' );
/**
* Add the necessary join to retrieve the category count for products.
*
* @param string $common_joins Existing common joins.
* @return string Modified common joins.
*/
function pwbe_common_joins_category_count( $common_joins ) {
global $wpdb;
$common_joins .= "
LEFT JOIN (
SELECT tr.object_id, COUNT(DISTINCT tt.term_taxonomy_id) as category_count
FROM {$wpdb->term_relationships} AS tr
INNER JOIN {$wpdb->term_taxonomy} AS tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
INNER JOIN {$wpdb->terms} AS t ON tt.term_id = t.term_id
WHERE tt.taxonomy = 'product_cat'
GROUP BY tr.object_id
) AS category_counts ON (category_counts.object_id = parent.ID)
";
return $common_joins;
}
add_filter( 'pwbe_common_joins', 'pwbe_common_joins_category_count' );
/**
* Modify the WHERE clause to filter products based on the category count.
*
* @param string $row_sql Existing row SQL.
* @param string $field_name Field name being filtered.
* @param string $filter_type Filter type.
* @param mixed $field_value Field value.
* @param mixed $field_value2 Second field value (if applicable).
* @param string $group_type Group type.
* @return string Modified row SQL.
*/
function pwbe_where_clause_category_count( $row_sql, $field_name, $filter_type, $field_value, $field_value2, $group_type ) {
if ( $field_name === 'category_count' ) {
$sql_builder = new PWBE_SQL_Builder();
$row_sql = $sql_builder->numeric_search( 'category_counts.category_count', $filter_type, $field_value, $field_value2 );
}
return $row_sql;
}
add_filter( 'pwbe_where_clause', 'pwbe_where_clause_category_count', 10, 6 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment