我正在为产品构建一个自定义表,我试图将简单的产品和变体添加到同一个表中。到目前为止我已经这样做了,但我需要修改变体产品的标题。我正在尝试采用这种格式: 》产品标题 黑色,8 英寸。”
我有这个代码:
foreach ($available_variations as $variation) {
//$attributes = $product->get_attributes();
$new_attributes = $variation['attributes'];
$data_array = array();
$allowed_attr = ['pa_color', 'pa_gauge', 'pa_size', 'pa_dimensions', 'pa_quantity', 'pa_length', 'pa_material'];
foreach ( $new_attributes as $meta_key => $meta ) {
$attr_label = wc_attribute_label( $meta_key, $product );
$attr_value = $product->get_attribute($meta_key);
array_push($data_array, $meta);
}
$attribute_sub = implode( ', ', $data_array );
回显时,这接近所需的格式。它的结尾是: 》产品标题 24 黑色,8 英寸
我只能在当前上下文中使用变体对象,是否有任何函数可以仅使用属性组 slug 和属性值来获取属性标签? 可能会像这样工作: get_attribute_lable("24-黑色", "pa_color"); --> 返回“黑色”
我尝试使用 wc_attribute_label 但它似乎只适用于属性组。 get_taxonomy 也只能从我尝试过的内容中获取组。如果我确实需要编写自定义函数,而无需打开 SQL 查询,最快的方法是什么?
我修改了您的代码以使用
get_term_by
函数,该函数根据属性的别名和分类法获取人类可读的属性术语。这允许您检索每个属性值的正确标签并以所需的方式格式化它。 wc_attribute_label
仍然检索属性组标签(例如“颜色”),但通过将其与 get_term_by
组合,我们可以获得特定的术语名称,从而允许您正确设置变体标题的格式,例如“产品标题黑色,8 英寸” ”。无需执行 SQL 查询。希望它有帮助...
foreach ($available_variations as $variation) {
//$attributes = $product->get_attributes();
$new_attributes = $variation['attributes'];
$data_array = array();
$allowed_attr = ['pa_color', 'pa_gauge', 'pa_size', 'pa_dimensions', 'pa_quantity', 'pa_length', 'pa_material'];
foreach ( $new_attributes as $meta_key => $meta_value ) {
// Get the attribute label (like "Color", "Size", etc.)
$attr_label = wc_attribute_label( $meta_key, $product );
// Get the term label for the attribute value (like "Black", "8 in.")
$term = get_term_by('slug', $meta_value, $meta_key);
if ($term) {
// Add the term name (like "Black") to the data array
$data_array[] = $term->name;
}
}
// Now we can implode the array to get the attribute sub-string
$attribute_sub = implode( ', ', $data_array );
// Example: Echo product title with attribute values appended
echo $variation['variation_title'] . ' ' . $attribute_sub; //It should Outputs: "Product Title Black, 8 in."
}