WooCommerce Variations How To Get Custom Field Names And Values ​​And Create Shorecodes

I have created a custom field in WooCommerce Product Variations. I was able to store information in this field for each specific variation. The code I used is the following and it works:

   add_action( 'woocommerce_variation_options_pricing', 'upf_add_custom_field_to_variations', 10, 3 );
 
function upf_add_custom_field_to_variations( $loop, $variation_data, $variation ) {
   woocommerce_wp_text_input( array(
'id' => 'custom_field[' . $loop . ']',
'class' => 'short',
'label' => __( 'Custom:', 'woocommerce' ),
'value' => get_post_meta( $variation->ID, 'custom_field', true )
   ) );
}
 
// ----------------------------------------- 
add_action( 'woocommerce_save_product_variation', 'upf_save_custom_field_variations', 10, 2 );
 
function upf_save_custom_field_variations( $variation_id, $i ) {
   $custom_field = $_POST['custom_field'][$i];
   if ( isset( $custom_field ) ) update_post_meta( $variation_id, 'custom_field', esc_attr( $custom_field ) );
} 
// ----------------------------------------- 
add_filter( 'woocommerce_available_variation', 'upf_add_custom_field_variation_data' );
 
function upf_add_custom_field_variation_data( $variations ) {
   $variations['custom_field'] = '<div class="woocommerce_custom_field">Custom: <span>' . get_post_meta( $variations[ 'variation_id' ], 'custom_field', true ) . '</span></div>';
   return $variations;
}

Now I want to make a short code to get the field name and value. If I create this shortcode I will be able to use this field in a custom page which is what I am aiming for. I tried various options but couldn’t find any way. Can you please help me complete my code. Thank You!

Leave a Comment