仅针对Woocommerce的特定类别获取价格

时间:2013-08-17 23:03:10

标签: wordpress woocommerce

我试图在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

0 个答案:

没有答案