I'm trying to add a custom field in the general section of a product and initialize it with a frontend form.
I had no problem in adding it, but I'm little lost on how to set it.
TO ADD AND SAVE THE CUSTOM FIELD:
// The code for displaying WooCommerce Product Custom Fields
add_action('woocommerce_product_options_general_product_data', 'woocommerce_product_custom_fields');
// Following code Saves WooCommerce Product Custom Fields
add_action('woocommerce_process_product_meta', 'woocommerce_product_custom_fields_save');
function woocommerce_product_custom_fields()
{
global $woocommerce, $post;
echo '<div class=" product_custom_field ">';
//Custom Product Text Field
woocommerce_wp_text_input(
array(
'id' => 'tipologiaAppunto',
'label' => __('Tipologia appunto:', 'woocommerce'),
'placeholder' => '',
'desc_tip' => 'true'
)
);
echo '</div>';
}
function woocommerce_product_custom_fields_save($post_id)
{
// Custom Product Text Field
$woocommerce_custom_product_text_field = $_POST['tipologiaAppunto'];
if (!empty($woocommerce_custom_product_text_field))
update_post_meta($post_id, 'tipologiaAppunto', esc_attr($woocommerce_custom_product_text_field));
}
To set it I've tried to extend the WC_PRODUCT CLASS
EXTENSION OF THE WC_PRODUCT CLASS:
add_action('init', 'register_myclass');
function register_myclass()
{
class WC_ProductExtended extends WC_Product
{
function __construct() {
parent::__construct();
if (!array_key_exists("tipologiaAppunto", $this->data)) {
$this->data["tipologiaAppunto"] = "";
}
}
/**
* Set product tipologiaAppunto.
*
* @since 3.0.0
* @param string $tipologiaAppunto Product tipologiaAppunto.
*/
public function set_tipologiaAppunto($tipologiaAppunto)
{
$this->set_prop( 'tipologiaAppunto', $tipologiaAppunto );
}
}
}
And now by calling the setter I was hoping to initialize the product custom field, but nothing happened.
$product->set_regular_price($_POST['price']);
$productExtendend = new WC_ProductExtended();
$productExtendend->set_tipologiaAppunto("Hey");
$productExtendend->save();
I don't know If this is the right I way, I found a lot of tutorial on how to add the custom field but so little on how to initialize it from the frontend, I've tried by mimic the behaviour of the existing fields but with no luck.