Reputation: 1
The below PHP code excludes Woocommerce categories from Google Merchant Centre. How would you combine the in_array
to make the code shorter?
// Exclude categories from my Google Product Feed
function lw_gpf_exclude_product($excluded, $product_id, $feed_format) {
// Return TRUE to exclude a product, FALSE to include it, $excluded to use the default behaviour.
$cats = wp_get_post_terms( $product_id, 'product_cat', array( 'fields' => 'ids' ) );
if ( in_array( 60, $cats ) ) {
return TRUE;
}
if ( in_array( 63, $cats ) ) {
return TRUE;
}
if ( in_array( 88, $cats ) ) {
return TRUE;
}
if ( in_array( 89, $cats ) ) {
return TRUE;
}
return $excluded;
}
add_filter( 'woocommerce_gpf_exclude_product', 'lw_gpf_exclude_product', 11, 3);
Upvotes: 0
Views: 120
Reputation: 695
use
in_array_any
function like this to make code shorter
function in_array_any($needles, $haystack) { return !!array_intersect($needles, $haystack); } if(in_array_any([60,63,88,89], $cats)){ return TRUE; }
Upvotes: 0
Reputation: 51
try this.
return !empty(array_intersect(array(60,63,88,89),$cats));
Upvotes: 0
Reputation: 92854
The solution using array_intersect
function:
...
if (array_intersect([60, 63, 88, 89], $cats)){
return TRUE;
}
Upvotes: 0
Reputation: 7034
If only one value is enough to return true, you can intersect both arrays and if the resulting array has a size (has elements), then at least one value is present in both arrays.
return count(array_intersect([60, 63, 88, 89], $cats)) > 0;
Upvotes: 2