Skip to content

Instantly share code, notes, and snippets.

@mattiasghodsian
Last active October 10, 2024 22:10
Show Gist options
  • Save mattiasghodsian/f70877da9d592f4d707ec19e9b555aa6 to your computer and use it in GitHub Desktop.
Save mattiasghodsian/f70877da9d592f4d707ec19e9b555aa6 to your computer and use it in GitHub Desktop.
[Woocommerce] Product Select2 input field
/**
* Title: [Woocommerce] Product Select2 input field
* Author: Mattias Ghodsian
* Description: Let's users search products in wp-admin / Woocommerce Product data
* Donate a cup of coffee: https://www.buymeacoffee.com/mattiasghodsian
* Donate Eth: 0xBBB96204E45D11C9799c6B12E6eE6F0d4A071Ef5
*/
function woocommerce_wp_product_select2( $field ) {
global $thepostid, $post, $woocommerce;
$thepostid = empty( $thepostid ) ? $post->ID : $thepostid;
$field['class'] = isset( $field['class'] ) ? $field['class'] : 'select short';
$field['wrapper_class'] = isset( $field['wrapper_class'] ) ? $field['wrapper_class'] : '';
$field['name'] = isset( $field['name'] ) ? $field['name'] : $field['id'];
echo '<p class="form-field ' . esc_attr( $field['id'] ) . '_field ' . esc_attr( $field['wrapper_class'] ) . '"><label for="' . esc_attr( $field['id'] ) . '">' . wp_kses_post( $field['label'] ) . '</label><select id="' . esc_attr( $field['id'] ) . '" name="' . esc_attr( $field['name'] ) . '" class="wc-product-search ' . esc_attr( $field['class'] ) . '" multiple="multiple">';
foreach ( $field['value'][0] as $key => $value ) {
echo '<option value="'.$value.'" selected="selected">'.wc_get_product( $value )->name.' (#'.$value.')</option>';
}
echo '</select> ';
if ( ! empty( $field['description'] ) ) {
if ( isset( $field['desc_tip'] ) && false !== $field['desc_tip'] ) {
echo '<span class="woocommerce-help-tip" data-tip="' . esc_attr( $field['description'] ) . '"></span>';
} else {
echo '<span class="description">' . wp_kses_post( $field['description'] ) . '</span>';
}
}
echo '</p>';
}
@mattiasghodsian
Copy link
Author

mattiasghodsian commented Dec 10, 2018

How to

$save_data = get_post_meta( $post->ID, 'save_data' );

woocommerce_wp_product_select2([
    'id'      => 'wc_product_ids',
    'label'   => __( 'Products', 'wc' ),
    'class' => '',
    'name' => 'wc_product_ids[]',
    'value'   => $save_data,
    'desc_tip' => true,
	'description' => __( 'Hello world', 'wc' ),
]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment