$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] 是一个数组,其中每个元素都是一个类别。in_array() 检查请求的值是否在数组中的任何位置。
测试它:
$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]);
产量:
True
Array
(
[0] => T-Shirts
[1] => Pants
)
更新
与您的代码集成:
$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';
如果您不希望某个类别在 $stack 数组中出现多次:
$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';