问题
I am trying to get a specific custom attribute in woocommerce. I've read tons of threads on this site which offer about 3-5 methods how to do it. After trying all, the only method that worked for me is to loop through all attributes - all others did not work. I have a custom attribute named 'pdfs'
The following tries did not work: (link)
$global product;
$myPdf = array_shift( wc_get_product_terms( $product->id, 'pdfs', array( 'fields' => 'names' ) ) );
$myPdf = $product->get_attribute( 'pdfs' );
$myPdf = get_post_meta($product->id, 'pdfs', true);
This is the only one that did work: (link)
$attributes = $product->get_attributes();
foreach ( $attributes as $attribute ) {
if (attribute_label( $attribute[ 'name' ] ) == "pdfs" ) {
echo array_shift( wc_get_product_terms( $product->id, $attribute[ 'name' ] ) );
}
}
I would much rather be able to use one of the first options
Any help would be appreciated.
Thanks
回答1:
Update: Added compatibility for Woocommerce 3+
As attributes are always prepend with pa_
in DB, for getting them with wc_get_product_terms()
function, you will need to use pa_pdfs
instead of pdfs
, this way:
global $product;
$product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id; // Added WC 3+ support
$myPdf = array_shift( wc_get_product_terms( $product_id, 'pa_pdfs', array( 'fields' => 'names' ) ) );
Reference: How to get a products custom attributes from WooCommerce
来源:https://stackoverflow.com/questions/38487561/woocommerce-get-custom-product-attribute