'Issue with saving custom field (custom post type) in WooCommerce coupon usage restriction tab
I'm trying to add a new field in the usage restriction of coupons.
Here is my code:
function add_coupon_cpt_field() {
$value = get_post_meta( $post->ID, '_select', true );
if( empty( $value ) ) $value = '';
$my_c_posts = get_posts( array(
'posts_per_page' => -1,
'orderby'=> 'date',
'order'=> 'DESC',
'post_type'=> 'tour',
'post_status'=> 'publish',
) );
$options[''] = __( 'Select a value', 'woocommerce'); // default value
foreach ($my_c_posts as $key => $post)
$options[$key] = $post->post_title;
echo '<div class="options_group">';
woocommerce_wp_select( array(
'id' => '_select',
'label' => __( 'Select Tour', 'woocommerce' ),
'options' => $options,
'value' => $value,
) );
echo '</div>';
}
add_action( 'woocommerce_coupon_options_usage_restriction', 'add_coupon_cpt_field', 10, 0 );
// Save Fields
add_action( 'woocommerce_coupon_options_save', 'custom_posts_fields_save' );
function custom_posts_fields_save( $post_id ){
$woocommerce_select = $_POST['_select'];
if( !empty( $woocommerce_select ) )
update_post_meta( $post_id, '_select', esc_attr( $woocommerce_select ) );
else {
update_post_meta( $post_id, '_select', '' );
}
}
The titles are displayed but when I save the coupon, the selection is not saved. Any advice?
Solution 1:[1]
Some comments/suggestions regarding your code attempt/question:
- Using
$value = get_post_meta( $post->ID, '_select', true );
is not necessary - In this answer I have used post type 'product' (since this is present by default in WooCommerce, adjust where necessary)
So you get:
// Add new field - usage restriction tab
function action_woocommerce_coupon_options_usage_restriction( $coupon_get_id, $coupon ) {
// Set post type
$post_type = 'product';
// Get posts
$my_c_posts = get_posts( array(
'posts_per_page' => -1,
'orderby' => 'date',
'order' => 'DESC',
'post_type' => $post_type,
'post_status' => 'publish',
) );
// Default value
$options[''] = __( 'Select a value', 'woocommerce' );
// Get post title
foreach ( $my_c_posts as $key => $post ) {
$options[$key] = $post->post_title;
}
// Output field
echo '<div class="options_group">';
woocommerce_wp_select( array(
'id' => '_select',
'label' => __( 'Select tour', 'woocommerce' ),
'options' => $options,
) );
echo '</div>';
}
add_action( 'woocommerce_coupon_options_usage_restriction', 'action_woocommerce_coupon_options_usage_restriction', 10, 2 );
// Save
function action_woocommerce_coupon_options_save( $post_id, $coupon ) {
// Isset
if ( isset ( $_POST['_select'] ) ) {
$coupon->update_meta_data( '_select', sanitize_text_field( $_POST['_select'] ) );
$coupon->save();
}
}
add_action( 'woocommerce_coupon_options_save', 'action_woocommerce_coupon_options_save', 10, 2 );
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |