php - WooCommerce:检查产品是否具有特定属性
问题描述
我想检查产品是否具有特定属性。但是该属性可能只是其中的一个。
例如,产品具有属性语言pa_sprog
,并且具有多种语言。但我想检查它是否包含“英语”语言。
我发现了这个很棒的代码(https://stackoverflow.com/a/60295332/1788961):
// for debug purposes, place in comment tags or delete this code
$product_attributes = $product->get_attributes();
echo '<pre>', print_r($product_attributes, 1), '</pre>';
// Get the product attribute value
$sprog = $product->get_attribute('pa_sprog');
// if product has attribute 'sprog' value(s)
if( $sprog == "english" ) {
echo '<div class="">yes!</div>';
} else {
echo '<div class="">no!</div>';
}
但是只有当语言“英语”是该属性的唯一值时,该代码才有效。如果有多个,则代码不再起作用。
我尝试更改 if 语句以检查语言是否在属性数组中:
if( in_array( "english", $sprog) ) {
但它不起作用。
还有其他方法吗?
解决方案
它不是 aarray
而是 a string
,因此您可以使用 astrpos
global $product;
// for debug purposes, place in comment tags or delete this code
$product_attributes = $product->get_attributes();
echo '<pre>', print_r($product_attributes, 1), '</pre>';
// Get the product attribute value
$sprog = $product->get_attribute('pa_sprog');
// Gettype - Returns the type of the PHP variable var.
echo gettype($sprog) . '<br>';
// Result
echo $sprog . '<br>';
// If product has attribute 'sprog' value(s)
if( strpos($sprog, 'english') !== false ) {
echo '<div class="">yes!</div>';
} else {
echo '<div class="">no!</div>';
}