We have previously learned how to display the number of sales for a specific product ID using a shortcode. However, this method does not work for variation IDs in WooCommerce, as WooCommerce only tracks sales for the parent product.

To address this issue, we will implement a different solution. One approach is to query the orders containing a specific variation ID and calculate the total sales from these orders. Alternatively, we can install a code snippet to begin tracking variation sales going forward, eliminating the need for manual querying and calculation.

In this case, we will explore the latter option. By implementing this snippet, we can accurately count variation sales from the moment it is installed. We will then create a shortcode to display this sales count anywhere, including within variation descriptions.

Stay tuned for more details on this method and how to use the shortcode effectively.

add_action( 'woocommerce_recorded_sales', 'bbloomer_maybe_update_variation_sales' );
 
function bbloomer_maybe_update_variation_sales( $order_id ) {
   $order = wc_get_order( $order_id );
   if ( ! $order ) return;
   if ( count( $order->get_items() ) > 0 ) {
      foreach ( $order->get_items() as $item ) {
         if ( 'product_variation' === get_post_type( $item->get_variation_id() ) ) {
            $variation_id = $item->get_variation_id();
            $total_sales = get_post_meta( $variation_id, '_total_sales', true ) ? get_post_meta( $variation_id, '_total_sales', true ) : 0;
            update_post_meta( $variation_id, '_total_sales', $total_sales + absint( $item->get_quantity() ) );
         }
      }
   }
}
 
// PART 2: variation sales shortcode
// usage: [var_sales id="123"]
 
add_shortcode( 'var_sales', 'bbloomer_sales_by_variation_id' );
 
function bbloomer_sales_by_variation_id( $atts ) {
   return get_post_meta( $atts['id'], '_total_sales', true ) ? get_post_meta( $atts['id'], '_total_sales', true ) : 0;
}