I have followed this answer How to add more custom field in Linked Product of Woocommerce to add a custom select field to my Linked Product screen in Woocommerce. This new field is meta key is subscription_toggle_product
.
It's working fine, but once you have selected a product, you can't delete it (there is no "Empty" option or cross symbol). I haven't got a clue how I can allow the selection to be deselected. I've tried adding an <option>
with an empty value, but it hasn't worked.
Here is my code:
// Display the custom fields in the "Linked Products" section
add_action( 'woocommerce_product_options_related', 'woocom_linked_products_data_custom_field' );
// Save to custom fields
add_action( 'woocommerce_process_product_meta', 'woocom_linked_products_data_custom_field_save' );
// Function to generate the custom fields
function woocom_linked_products_data_custom_field() {
global $woocommerce, $post;
$product = wc_get_product( $post->ID );
?>
<p class="form-field">
<label for="subscription_toggle_product"><?php _e( 'Subscription Toggle Product', 'woocommerce' ); ?></label>
<select class="wc-product-search" style="width: 50%;" id="subscription_toggle_product" name="subscription_toggle_product" data-placeholder="<?php esc_attr_e( 'Search for a product…', 'woocommerce' ); ?>" data-action="woocommerce_json_search_products_and_variations" data-exclude="<?php echo intval( $post->ID ); ?>">
<?php
$product_id = get_post_meta( $post->ID, '_subscription_toggle_product_id', true );
if ( $product_id ) {
$product = wc_get_product( $product_id );
if ( is_object( $product ) ) {
echo '<option value="' . esc_attr( $product_id ) . '"' . selected( true, true, false ) . '>' . wp_kses_post( $product->get_formatted_name() ) . '</option>';
}
}
?>
</select>
</p>
<?php
}
// Function the save the custom fields
function woocom_linked_products_data_custom_field_save( $post_id ){
if (isset($_POST['subscription_toggle_product'])) {
$product_field_type = $_POST['subscription_toggle_product'];
update_post_meta( $post_id, '_subscription_toggle_product_id', $product_field_type );
}
}
This kind of select field only works with a defined
multiple
attribute and work with an array of values. so you can't use it for a simple ID. If you add to your select fieldmultiple="multiple"
attribute it will work.Also since Woocommerce 3 things have changed:
- There are better hooks to save the data.
- You can now use CRUD Objects and related methods.
The following code will work for multiple product IDs (an array of products IDs):
Code goes in function.php file of your active child theme (active theme). Tested and works.