Question

I am using php to extract category names from a series of woocommerce (wordpress) cart items like so:

<?php $stack = array();
    foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
    $_product = $values['data'];
    $category = $_product->get_categories();
    array_push($stack, $category);              
}

If there are two products in the cart, each with a different category, the output of print_r($stack) might be: Array ( [0] => Thanksgiving [1] => Poultry )

Regardless of products, I need to run conditional statements like so:

if (in_array( 'T-Shirts', $stack[1] )) echo "True"; else echo "False";

The above conditional is only looking at the 2nd item in the array, not all. How do I search through all items in array?

Was it helpful?

Solution

$category = $_product->get_categories();
preg_match_all("`<[^>]+>([^<]+)</[^>]+>`", $category, $categories);
if ( in_array( 'Pants', $categories[1] ) ) {
?>
    <h2>This product has Pants, and potentially other categories</h2>
<?php
}

$categories[1] is an array where each element is a single category. in_array() checks to see if the requested value is ANYWHERE in the array.

Test it:

$category = '<a href="linktocategorypage" rel="tag">T-Shirts</a><a href="linktocategorypage" rel="tag">Pants</a>';
preg_match_all("`<[^>]+>([^<]+)</[^>]+>`", $category, $categories);
$pants = in_array( 'Pants', $categories[1] );
if ($pants) echo "True"; else echo "False";
print_r($categories[1]);

yields:

True

Array
(
    [0] => T-Shirts
    [1] => Pants
)

Update

Integrating with your code:

$stack = array();
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
    $_product = $values['data'];
    $category = $_product->get_categories();
    preg_match_all("`<[^>]+>([^<]+)</[^>]+>`", $category, $categories);
    foreach( $categories[1] as $cat) $stack[] = $cat;  // Could also use array_merge here
}

if( in_array( 'Pants', $stack ) ) echo 'We have pants';
else echo 'We do not have pants';

If you don't want a category to appear more than once in the $stack array:

$stack = array();
foreach ( $woocommerce->cart->get_cart() as $cart_item_key => $values ) {
    $_product = $values['data'];
    $category = $_product->get_categories();
    preg_match_all("`<[^>]+>([^<]+)</[^>]+>`", $category, $categories);
    foreach( $categories[1] as $cat) {
        if ( !in_array( $cat, $stack ) ) $stack[] = $cat;
    }
}

if( in_array( 'Pants', $stack ) ) echo 'We have pants';
else echo 'We do not have pants';
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top