Skip to content
Advertisement

Woocommerce: How to display SKU for variable product options dropdown

How I can view the SKU code in the dropdown option for the variable products? I have tried to use this code but it is only to view the price option in woocommerce. Cause recently I use the other code but the SKU not dynamically when I change and variable option.

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 .')';
    }
  }
}

Base on this code how could I assign the get-sku and view beside the variation option area in front end display.If anyone could help me to solve a problem I really appriciate that.

Advertisement

Answer

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 );
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement