猿问

电子商务:如何显示可变产品选项下拉列表的 SKU

如何在可变产品的下拉选项中查看 SKU 代码?我试图使用此代码,但它只是为了在woocommerce中查看价格选项。原因最近我使用其他代码,但 SKU 不是动态的,当我更改和变量选项。


add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name' );


function display_price_in_variation_option_name( $term ) {

  global $wpdb, $product;


  if( isset( $product ) ) {


    $result = $wpdb->get_col( "SELECT slug FROM {$wpdb->prefix}terms WHERE name = '$term'" );


    $term_slug = ( !empty( $result ) ) ? $result[0] : $term;


    $query = sprintf( "SELECT postmeta.post_id AS product_id

      FROM {$wpdb->prefix}postmeta postmeta

      LEFT JOIN {$wpdb->prefix}posts products ON ( products.id = postmeta.post_id )

      WHERE postmeta.meta_key LIKE 'attribute_%%'

      AND postmeta.meta_value = '%s'

      AND products.post_parent = %d", $term_slug, $product->get_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 (wc_price( $_product->get_price() ));

      //this is where you can actually customize how the price is displayed

      return $term . ' ('. $itemPrice .')';

    }

  }

}

基于此代码,我如何分配 get-sku 并在前端显示的变体选项区域旁边查看。如果有人能帮助我解决问题,我真的知道。


慕桂英3389331
浏览 108回答 1
1回答

阿晨1998

function display_price_in_variation_option_name( $term ) {    global $wpdb, $product;    if( isset( $product ) ) {        $query = sprintf( "SELECT postmeta.post_id AS product_id            FROM {$wpdb->prefix}postmeta postmeta            LEFT JOIN {$wpdb->prefix}posts products ON ( products.id = postmeta.post_id )            WHERE postmeta.meta_key LIKE 'attribute_%%'            AND postmeta.meta_value = '%s'            AND products.post_parent = %d", $term, $product->get_id() );        $results = $wpdb->get_results( $query );        foreach ($results as $key => $result) {            $variation_id = $result->product_id;        }        $variation_sku = get_post_meta( $variation_id , '_sku', TRUE );        $term = $term . ' ('. $variation_sku .')';    }    return $term;}add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name', 10, 1 );
随时随地看视频慕课网APP
我要回答