I have a some product custom fields in WooCommerce and it works well. Here's the code:
add_action( 'woocommerce_product_options_advanced', 'meta_data_custom' );
function meta_data_custom() {
// 1. Partner ID
woocommerce_wp_text_input( array(
'id' => '_idpartner',
'label' => __( 'Partner ID', 'woocommerce' ),
'description' => __( 'Fill in your partner ID.', 'woocommerce' ),
'desc_tip' => true,
'placeholder' => __( 'Ex : P1', 'woocommerce' )
) );
// 2. Referral ID
woocommerce_wp_text_input( array(
'id' => '_idreferral',
'label' => __( 'Referral ID', 'woocommerce' ),
'description' => __( 'Fill in your referral ID.', 'woocommerce' ),
'desc_tip' => true,
'placeholder' => __( 'Ex : R1', 'woocommerce' )
) );
}
// Save custom field
add_action( 'woocommerce_admin_process_product_object', 'action_woocommerce_admin_process_product_object_meta_data_custom', 10, 3 );
function action_woocommerce_admin_process_product_object_meta_data_custom($product){
// 1. ID Partner
if ( isset( $_POST['_idpartner'] ) ) {
// Update
$product->update_meta_data( '_idpartner', sanitize_text_field( $_POST['_idpartner'] ) );
}
// 1. ID Referral
if ( isset( $_POST['_idreferral'] ) ) {
// Update
$product->update_meta_data( '_idreferral', sanitize_text_field( $_POST['_idreferral'] ) );
}
}
Both the Partner ID and the Referral ID, must be filled in before the product is published. All Partner ID already have a referral ID except for (Partner ID == P1). So, I want to fill referral ID automatically other than partner ID P1.
So far I have tried :
function update_meta_data_custom(){
global $product;
$idpartner = $product->get_meta('_idpartner');
$idreferral = $product->get_meta('_idreferral');
//Set referral id Obtained from user meta dinamically
$idreferral = "R13";//examples only
if(!empty($idpartner)){
if($idpartner !== "P1"){
//$product->update_meta_data( '_idreferral', sanitize_text_field( $_POST['_idreferral'] ) );
//update _idreferral with $idreferral
}
else{
if(!$idreferral){
//Give a message to update referral ID or no need to do anything
//Just in case something by human error
}
else{
//No need to do anything or keep the data
}
}
}
else{
//Give a message to update partner ID or no need to do anything
//Just in case something by human error
}
}
but not sure how to achieve it.
Can someone walk me through how to do that?
Note that you will need to replace in the second function below,
$referral_id = "R13";with the code for referral ID obtained dynamically from user meta.So you can implement your custom metadata update based on certain conditions replacing your current code, with the following:
Code goes in functions.php file of your child theme (or in a plugin). It should work
When saving/updating the product, if the Partner ID or/and the Referral ID are empty, an error notice will be displayed.