我试图在 Woocommerce 的变体旁边显示价格,我可以做得很好。现在,我不想显示所有变体的价格,而只想在属于特定类别的变体旁边显示价格。
这是我迄今为止提出的,从逻辑上讲它是有道理的,但不是在这个特定的类别上工作。有关如何排除故障的任何建议?
//get prices of variations
function display_price_in_variation_option_name( $term ) {
global $wpdb, $product;
$result = $wpdb->get_col( "SELECT slug FROM {$wpdb->prefix}terms WHERE name = '$term'" );
$term_slug = ( !empty( $result ) ) ? $result[0] : $term;
$query = "SELECT postmeta.post_id AS product_id
FROM {$wpdb->prefix}postmeta AS postmeta
LEFT JOIN {$wpdb->prefix}posts AS products ON ( products.ID = postmeta.post_id )
WHERE postmeta.meta_key LIKE 'attribute_%'
AND postmeta.meta_value = '$term_slug'
AND products.post_parent = $product->id";
$variation_id = $wpdb->get_col( $query );
$parent = wp_get_post_parent_id( $variation_id[0] );
if ( $parent > 0 ) {
$_product = new WC_Product_Variation( $variation_id[0] );
$itemPrice = strip_tags (woocommerce_price( $_product->get_price() ));
//this is where you can actually customize how the price is displayed
return $term . ' (' . $itemPrice . ')';
}
return $term;
//Add prices to variations
global $post;
$terms = wp_get_post_terms( $post->ID, 'product_cat' );
foreach ( $terms as $termItem ) $categories[] = $termItem->slug;
if ( in_array( 'custom-pet-portrait-painting', $categories ) ) {
add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name' );
} //end function
}
或者我可以使用 get_terms 来包装下面显示变化价格的代码吗?我几乎只需要显示与一个类别有关的变化的价格。
if (has_term ('my-category', 'product_cat')) {
//get prices of variations
function display_price_in_variation_option_name( $term ) {
global $wpdb, $product;
$result = $wpdb->get_col( "SELECT slug FROM {$wpdb->prefix}terms WHERE name = '$term'" );
$term_slug = ( !empty( $result ) ) ? $result[0] : $term;
$query = "SELECT postmeta.post_id AS product_id
FROM {$wpdb->prefix}postmeta AS postmeta
LEFT JOIN {$wpdb->prefix}posts AS products ON ( products.ID = postmeta.post_id )
WHERE postmeta.meta_key LIKE 'attribute_%'
AND postmeta.meta_value = '$term_slug'
AND products.post_parent = $product->id";
$variation_id = $wpdb->get_col( $query );
$parent = wp_get_post_parent_id( $variation_id[0] );
if ( $parent > 0 ) {
$_product = new WC_Product_Variation( $variation_id[0] );
$itemPrice = strip_tags (woocommerce_price( $_product->get_price() ));
//this is where you can actually customize how the price is displayed
return $term . ' (' . $itemPrice . ')';
}
return $term;
add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name' );
} //end has_term