0

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);
1

4 Answers 4

2

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;
Sign up to request clarification or add additional context in comments.

Comments

0

The solution using array_intersect function:

...
if (array_intersect([60, 63, 88, 89], $cats)){
    return TRUE;
}

Comments

0

try this.

return !empty(array_intersect(array(60,63,88,89),$cats));

Comments

0

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;
    }

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.