-
-
Save tommcfarlin/91e9a7916e171dcab3bd845ee9025412 to your computer and use it in GitHub Desktop.
[WordPress] Programmatically Add a WooCommerce Variable Product
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 | |
); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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 ); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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