Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[WordPress] Programmatically Add a WooCommerce Variable Product
<?php
public function init() {
add_action(
'woocommerce_product_after_variable_attributes',
array( $this, 'variations_field' ),
10, 3
);
add_action(
'woocommerce_save_product_variation',
array( $this, 'add_custom_variations_save' ),
10, 2
);
}
<?php
public function variations_field( $loop, $variation_data, $variation ) {
$description = sanitize_text_field(
'Enter a information to display to the customer of this product.'
);
$args = array(
'id' => $this->variations,
'label' => sanitize_text_field( 'VHX Package IDs' ),
'placeholder' => '',
'desc_tip' => true,
'description' => $description,
'value' => get_post_meta( $variation->ID, $this->variations, true ),
);
woocommerce_wp_text_input( $args );
}
<?php
public function add_custom_variations_save( $post_id ) {
if ( ! ( isset( $_POST[ $this->variations ] ) || wp_verify_nonce( sanitize_key( $_POST['security'] ), 'woocommerce_save_variations' ) ) ) { // Input var okay.
return false;
}
$variations = sanitize_text_field(
wp_unslash( $_POST[ $this->variations ] ) // Input var okay.
)
);
update_post_meta(
$post_id,
$this->variations,
esc_attr( $variations )
);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment