Skip to content

Instantly share code, notes, and snippets.

@plugin-republic
Created June 10, 2018 14:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save plugin-republic/23bd2ba28d31cdbb4eeccfac0878547c to your computer and use it in GitHub Desktop.
Save plugin-republic/23bd2ba28d31cdbb4eeccfac0878547c to your computer and use it in GitHub Desktop.
<?php
/**
* Add a custom text field to a variable subscription product
* @since 1.0.0
*/
function prefix_display_fields( $loop, $variation_data, $variation ) {
$custom_field_value = get_post_meta( $variation->ID, 'my_custom_field', true );
?>
<div class="variable_subscription_pricing show_if_variable-subscription">
<p class="form-row form-row-first form-field show_if_variable-subscription _subscription_my_custom_field">
<label for="variable_subscription_my_custom_field[<?php echo esc_attr( $loop ); ?>]">
<?php
// translators: placeholder is a currency symbol / code
echo esc_html__( 'My Custom Field', 'text-domain' );
?>
</label>
<input type="text" class="wc_input_my_custom_field" name="variable_my_custom_field[<?php echo esc_attr( $loop ); ?>]" value="<?php echo esc_attr( $custom_value ); ?>" placeholder="<?php echo esc_attr_x( 'e.g. Hello', 'example text', 'text-domain' ); ?>">
</p>
</div>
<?php
}
add_action( 'woocommerce_variable_subscription_pricing', 'prefix_display_fields', 10, 3 );
/**
* Save the custom field
* @since 1.0.0
*/
function prefix_save_product_variation( $variation_id, $index ) {
if ( isset( $_POST['variable_my_custom_field'][ $index ] ) ) {
$variable_my_custom_field = sanitize_text_field( $_POST['variable_my_custom_field'][ $index ] );
update_post_meta( $variation_id, 'variable_my_custom_field', $variable_my_custom_field );
}
}
add_action( 'woocommerce_save_product_variation', 'prefix_save_product_variation', 20, 2 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment