在条件标签中使用产品属性

时间:2018-02-28 作者:Miguel Gomes

我有以下代码,将价格添加到每个变体旁边:

//Add prices to variations
add_filter( \'woocommerce_variation_option_name\', \'display_price_in_variation_option_name\' );

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] );

//this is where you can actually customize how the price is displayed
return $term . \' <span>(\' . woocommerce_price( $_product->get_price() ) . \')</span>\';
}
return $term;

}
此代码工作正常。然而,我希望该代码只应用于特定的产品属性(slug是培训级别)。如果使用if语句和条件标记,这可能吗?

我还尝试添加以下内容global $wpdb, $product; 但不起作用:

$product_name = $product->get_attribute( \'training-level\' );
请帮忙。

1 个回复
SO网友:Xhynk

如果$term 变量匹配某个值。

我不确定是什么$term 实际上包含,但这应该有效。如果没有,则可以修改if 声明。

//Add prices to variations
add_filter( \'woocommerce_variation_option_name\', \'display_price_in_variation_option_name\' );
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] );

        if( $term == \'Beginner Level\' || $term == \'Intermediate Level\' || $term == \'Advanced Level\' ){
            //this is where you can actually customize how the price is displayed
            return $term . \' <span>(\' . woocommerce_price( $_product->get_price() ) . \')</span>\';
        } else {
            return $term;
        }
    }
    return $term;
}

结束

相关推荐