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 field multiple="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):
// Display a custom select field in "Linked Products" section
add_action( 'woocommerce_product_options_related', 'display_linked_products_data_custom_field' );
function display_linked_products_data_custom_field() {
global $product_object, $post;
?>
<p class="form-field">
<label for="subscription_toggle_products"><?php _e( 'Subscription Toggle Products', 'woocommerce' ); ?></label>
<select class="wc-product-search" multiple="multiple" style="width: 50%;" id="subscription_toggle_ids" name="_subscription_toggle_ids[]" 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_ids = $product_object->get_meta( '_subscription_toggle_ids' );
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>
</p>
<?php
}
// Save the values to the product
add_action( 'woocommerce_admin_process_product_object', 'save_linked_products_data_custom_field_value', 10, 1 );
function save_linked_products_data_custom_field_value( $product ){
$data = isset( $_POST['_subscription_toggle_ids'] ) ? array_map( 'intval', (array) $_POST['_subscription_toggle_ids'] ) : array();
$product->update_meta_data( '_subscription_toggle_ids', $data );
}
Code goes in function.php file of your active child theme (active theme). Tested and works.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…