I have successfully added a product search field in my edit product page, but I need to be able to clear the selection. How can I achieve this?
Alternatively: how do I manage to only be able to select 1 product if I set multiple on the select component?
My code looks like below:
add_action('woocommerce_product_data_panels', function() {
global $post, $woocommerce;
$product_ids = get_post_meta( $post->ID, '_stock_sync_data_ids', true );
if( empty($product_ids) )
$product_ids = array();
?>
<div id="stock_sync_data" class="panel woocommerce_options_panel hidden">
<?php if ( $woocommerce->version >= '3.0' ) : ?>
<p class="form-field stock_sync_data">
<label for="stock_sync_data"><?php _e( 'Select product to sync with. (Only select 1 item)', 'woocommerce' ); ?></label>
<select class="wc-product-search" style="width: 50%;" id="stock_sync_data" name="stock_sync_data[]" data-placeholder="<?php esc_attr_e( 'Search for a product…', 'woocommerce' ); ?>" data-action="woocommerce_json_search_products_and_variations">
<?php
foreach ( $product_ids as $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> <?php echo wc_help_tip( __( 'Select product to syncronize stock.', 'woocommerce' ) ); ?>
</p>
<?php endif; ?>
</div>
<?php
});
