在 WooCommerce 中,我定义了添加/定义了一些产品属性及其名称,并且编写了一些代码,允许我在可变产品级别定义替代属性标签名称。
因此,例如,在单个产品页面中,对于某些产品,属性“颜色”可以显示为“T 恤颜色”,而在其他一些产品上,属性“颜色”可以显示为“帽子颜色”。这样,我可以灵活地对不同类型的项目使用相同的属性,但在前端显示不同的属性标签名称。
// Create text input where text for custom label will be entered
add_action('woocommerce_product_options_attributes', 'add_custom_attribute_label_fields');
function add_custom_attribute_label_fields() {
global $post;
// Get the product attributes
$product_attributes = maybe_unserialize(get_post_meta($post->ID, '_product_attributes', true));
if (!empty($product_attributes)) {
echo '<div class="options_group">';
foreach ($product_attributes as $attribute_name => $attribute) {
if ($attribute['is_taxonomy']) {
$field_id = 'custom_attribute_label_' . $attribute_name;
$label = get_post_meta($post->ID, $field_id, true);
woocommerce_wp_text_input(array(
'id' => $field_id,
'label' => 'Name of the ATTRIBUTE ' . esc_html(wc_attribute_label($attribute["name"])) . ' for that product.',
'description' => esc_html('Please enter the name of that You would like to e shown at the single product page.'),
'desc_tip' => true,
'value' => esc_attr($label),
));
}
}
echo '</div>';
}
}
// Save the custom attribute labels
add_action('woocommerce_admin_process_product_object', 'save_custom_attribute_labels');
function save_custom_attribute_labels($product) {
$product_id = $product->get_id();
// Get the product attributes
$product_attributes = maybe_unserialize(get_post_meta($product_id, '_product_attributes', true));
if (!empty($product_attributes)) {
foreach ($product_attributes as $attribute_name => $attribute) {
if ($attribute['is_taxonomy']) {
$field_id = 'custom_attribute_label_' . $attribute_name;
if (isset($_POST[$field_id])) {
update_post_meta($product_id, $field_id, sanitize_text_field($_POST[$field_id]));
}
}
}
}
}
// Filter to display custom attribute label
add_filter('woocommerce_attribute_label', 'custom_attribute_label', 100, 3);
function custom_attribute_label($label, $name, $attproduct) {
// Ensure $attproduct is an instance of WC_Product
if (is_a($attproduct, 'WC_Product')) {
$product_id = $attproduct->get_id();
// Retrieve the custom label
$custom_label = get_post_meta($product_id, 'custom_attribute_label_' . $name, true);
// Check if custom label is not empty and return it
if (!empty($custom_label)) {
return $custom_label;
}
}
}
但我无法让它工作。如果我在函数“自定义属性标签”中插入一些“回声”,那么我就可以在变体表单中看到保存的替代属性标签,并重复与该产品的变体数量相同的次数。但产品属性标签名称仍为旧名称。