问题
In woocommerce, If a specific product attribute has a value, then I would like to display its corresponding text/value on product single product pages under the price.
How to check if a specific product attribute has a value? How to get a specific product attribute name and value to display it in single product pages?
回答1:
The following will display a specific product attribute label name + values under the price in single product pages only if it has a value.
This can be done using WC_Product method get_attribute().
You will have to define your product attribute slug inside the function…
The hooked function:
add_action( 'woocommerce_single_product_summary', 'product_attribute_after_price', 15 );
function product_attribute_after_price () {
global $product;
// HERE add your product attribute SLUG or taxonomy
$attribute_slug = 'color';
$taxonomy = strpos($url, 'blog') !== false ? $attribute_slug : 'pa_' . $attribute_slug;
$attribute_name = get_taxonomy( $taxonomy )->labels->singular_name;
$term_name = $product->get_attribute( $taxonomy ); // The value
if( empty($term_name) ) return; // Exit if empty value
// If not empty we display it
$output = '<div class="product-attribute '.$taxonomy.'"><p>';
$output .= '<strong> '.$attribute_name.'</strong>: ';
$output .= '<span> '.$term_name.'</span>';
echo $output . '</p></div>';
}
Code goes in function.php file of your active child theme (or active theme). Tested and work.
来源:https://stackoverflow.com/questions/49793674/display-specific-product-attribute-in-woocommerce-single-product-pages-below-pri