在下拉列表中显示Woocommerce变动价格和库存状态

时间:2018-10-08 10:04:00

标签: woocommerce

我希望在下拉列表中显示每个woocommerce产品版本的价格和库存状态,如下所示:价格-版本名称-库存状态。

以下代码在下拉列表中为我提供了价格和品种名称,但是我不确定添加每种品种当前库存状态所需的其他代码吗?

// Add Variation Price to Drop Down

add_filter( 'woocommerce_variation_option_name', 
'display_price_in_variation_option_name' );

function display_price_in_variation_option_name( $term ) {
global $wpdb, $product;

if ( empty( $term ) ) return $term;
if ( empty( $product->id ) ) return $term;

$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] );
     return wp_kses( woocommerce_price( $_product->get_price() ), array() ). ' - ' . $term . '';
}
return $term;

}

预先感谢您的帮助。

2 个答案:

答案 0 :(得分:2)

我已通过删除自定义sql查询修改了您的函数,并使用WooCommerce内置函数来实现目标。

Public Function max(x, y As Variant) As Variant
  max = IIf(x > y, x, y)
End Function

Public Function min(x, y As Variant) As Variant
   min = IIf(x < y, x, y)
End Function

注意::如果每种产品的一个属性未组合在一起,则此功能将正常工作。

输出:

enter image description here

答案 1 :(得分:0)

只要其他人想在自定义下拉菜单中添加带有自定义措词的库存状态,这就是我根据Kashalo提供的答案使用的代码。

add_filter( 'woocommerce_variation_option_name','display_price_in_variation_option_name');

function display_price_in_variation_option_name( $term ) {
global $product;

if ( empty( $term ) ) {
    return $term;
}
if ( empty( $product->id ) ) {
    return $term;
}

$variation_id = $product->get_children();


foreach ( $variation_id as $id ) {
    $_product       = new WC_Product_Variation( $id );
    $variation_data = $_product->get_variation_attributes();
    $stock_status = $_product->get_stock_status();
    $stock_status = str_replace( array('instock','outofstock','onbackorder'), array('In Stock','Out of Stock','Please allow a few extra days for delivery'), $stock_status );

    foreach ( $variation_data as $key => $data ) {

        if ( $data == $term ) {
            $html  = wp_kses( woocommerce_price( $_product->get_price() ), array() );
            $html .= ' - ' . $term;
            $html .= ( $stock_status ) ? ' - ' . $stock_status : '';
            return $html;
        }
    }
}

return $term;

}