I'm trying to modify a filter defined in a Wordpress/Woocommerce plugin. The filter is defined in the plugin as follows:
$product_objects = apply_filters('list_products_objects', array_map('wc_get_product', $ids));
$ids is an array of product_ids
$ids = array();
This code doesn't get executed
add_filter('remove_product_ids', 'list_products_objects', 10, 2 );
function remove_product_ids($product_ids) {
$new_product_ids = array();
if ( is_array($product_ids) ) {
if ( !empty ($product_ids) ) {
foreach( $product_ids as $key => $product_id ) {
if ( in_array( get_the_terms( $product_id, 'product_cat' ), array( 'mugs','tshirts' ) ) ) { //Add the slug name here to include
$new_product_ids[] = $product_id;
}
}
$product_ids = $new_product_ids;
}
}
return $product_ids;
}
and this throws a PHP parse error
function remove_product_ids(array_map('wc_get_product', $product_ids)) {
have searched for answers on the web but wasn't able to find a comparable problem. What could be a solution to make this filter run?
The filter receives an array of product objects, so the callback needs to expect that, and not an array of IDs. The array_map()
function applies a function to every item in the array, and then saves that result back to the array. So in this case, array_map()
takes an ID, gets the product for that ID, and saves it back into the array. Also, the filter name does not match.
Untested:
add_filter( 'list_products_objects', static function ( $products ) {
if ( empty( $products ) || ! is_array( $products ) ) {
return $products;
}
// Remove any empty entries.
$products = array_filter( $products );
$filtered_products = array();
foreach ( $products as $product ) {
if ( ! has_term( array( 'mugs', 'tshirts' ), 'product_cat', $product->get_id() ) ) {
continue;
}
$filtered_products = $product;
}
return $filtered_products;
} );