add product search field in woo-commerce product page

right now i am using below code

// Display Fields
add_action( 'woocommerce_product_options_general_product_data', 'woo_add_custom_general_fields' );
 function woo_add_custom_general_fields() {


  global $woocommerce, $post;


  echo '<div class="options_group">';


  // Custom fields will be created here...

// Product Select
?>
<p class="form-field product_field_type">
<label for="product_field_type"><?php _e( 'Product Select', 'woocommerce' ); ?></label>
<select style="width:100%" id="product_field_type" name="product_field_type[]" class="ajax_chosen_select_products" multiple="multiple" data-placeholder="<?php _e( 'Search for a product&hellip;', 'woocommerce' ); ?>">
    <?php
        $product_field_type_ids = get_post_meta( $post->ID, '_product_field_type_ids', true );
        $product_ids = ! empty( $product_field_type_ids ) ? array_map( 'absint',  $product_field_type_ids ) : null;
        if ( $product_ids ) {
            foreach ( $product_ids as $product_id ) {

                $product      = get_product( $product_id );
                $product_name = woocommerce_get_formatted_product_name( $product );

                echo '<option value="' . esc_attr( $product_id ) . '" selected="selected">' . esc_html( $product_name ) . '</option>';
            }
        }
    ?>
</select> <img class="help_tip" data-tip='<?php _e( 'Your description here', 'woocommerce' ) ?>' src="<?php echo $woocommerce->plugin_url(); ?>/assets/images/help.png" height="16" width="16" />
</p>
<?php

  echo '</div>';

}

which shows below product field but not working properly

Read More

enter image description here

but i wants product search like below pic

enter image description here

I am using below website for code

http://www.remicorson.com/mastering-woocommerce-products-custom-fields/

Related posts

5 comments

  1. I was trying to figure out the same problem for a client of mine recently. I had originally used that same tutorial to add a custom product search input field for him on the back end and it broke when we got him updated to WooCommerce 2.5+.

    To add the product search widget/field to the backend:

    ?>
    
        <p class="form-field product_field_type">
        <label for="product_field_type_ids"><?php _e( 'Component Products:', 'woocommerce' ); ?></label>
    
            <input type="hidden" class="wc-product-search" style="width: 50%;" id="product_field_type_ids" name="product_field_type_ids" data-placeholder="<?php esc_attr_e( 'Search for a product&hellip;', 'woocommerce' ); ?>" data-action="woocommerce_json_search_products" data-multiple="true" data-exclude="<?php echo intval( $post->ID ); ?>" data-selected="<?php
                            $product_ids = array_filter( array_map( 'absint', (array) get_post_meta( $post->ID, '_product_field_type_ids', true ) ) );
                            $json_ids    = array();
    
                            foreach ( $product_ids as $product_id ) {
                                $product = wc_get_product( $product_id );
                                if ( is_object( $product ) ) {
                                    $json_ids[ $product_id ] = wp_kses_post( html_entity_decode( $product->get_formatted_name(), ENT_QUOTES, get_bloginfo( 'charset' ) ) );
                                }
                            }
    
                            echo esc_attr( json_encode( $json_ids ) );
                        ?>" value="<?php echo implode( ',', array_keys( $json_ids ) ); ?>" /> <?php echo wc_help_tip( __( 'Select component parts to display on the product page.', 'woocommerce' ) ); ?>
        </p>
    
        <?php
    

    To Save: (saved in the same id int array format as the existing field so you don’t have to start from scratch with your existing database entries)

    $my_product_ids    = isset( $_POST['product_field_type_ids'] ) ? array_filter( array_map( 'intval', explode( ',', $_POST['product_field_type_ids'] ) ) ) : array();
        update_post_meta( $post_id, '_product_field_type_ids', $my_product_ids  );
    

    To display on the front end: (same as before)

    global $post;
    $items = get_post_meta($post->ID, '_product_field_type_ids', true);
    if (! empty($items)) {
            foreach ( $items as $product_id ) {
                echo '<div class="productLink"><a href="'.get_permalink($product_id).'">'.get_the_title($product_id).'</a></div>';
            }  
        }
    
  2. I copied this code from up-sells. This is only the search form.

    <p class="form-field">
            <label for="upsell_ids"><?php _e( 'Up-sells', 'woocommerce' ); ?></label>
            <select class="wc-product-search" multiple="multiple" style="width: 50%;" id="upsell_ids" name="upsell_ids[]" data-placeholder="<?php esc_attr_e( 'Search for a product&hellip;', 'woocommerce' ); ?>" data-action="woocommerce_json_search_products_and_variations" data-exclude="<?php echo intval( $post->ID ); ?>">
                <?php
                $product_object = new WC_Product($post->ID);
                $product_ids = $product_object->get_upsell_ids( 'edit' );
    
                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( __( 'Up-sells are products which you recommend instead of the currently viewed product, for example, products that are more profitable or better quality or more expensive.', 'woocommerce' ) ); ?>
    </p>
    
  3. This answer is a great starting point but there are some changes required to make this work with the latest WooCommerce releases where the product search field has changed from a input with type=hidden to a select with a multiple attribute.

    Backend input field

    You can use the backend HTML of the WooCommerce upsells field, which you can find here on GitHub, as a template for your own backend field.

    Saving the backend input field

    You can use the following code to retrieve the selected items and save there ids as post meta.

    $my_product_ids = isset($_POST['product_field_type_ids']) ? array_map('intval', explode(',', (array) $_POST['product_field_type_ids'])) : array();
    update_post_meta($post_id, '_product_field_type_ids', $my_product_ids);
    
  4. A more general solution (not only on product page but also on all other pages) is described here: https://www.binarycarpenter.com/create-woocommerce-products-search-input-for-your-plugins/
    and the code is here:
    https://github.com/datmt/WooCommerce-Ajax-Product-Search

    Minimum working example based on the above mentioned code:

    1.Append the jquerys select2 script and your own my_product_search_script.js like this. Put this next to your function:

    class BC_AJAX_Product_Search {
        public function __construct() {
            add_action('admin_enqueue_scripts', array($this, 'enqueue_admin'));
        }
        public function enqueue_admin() {
            wp_register_style('my-plugin-select2-style', 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css');
            wp_enqueue_style('my-plugin-select2-style');
            wp_register_script('my-plugin-select2-script', 'https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js', array('jquery'));
            wp_register_script('my-plugin-script', plugins_url('my_product_search_script.js', __FILE__), array('jquery'));
            wp_enqueue_script('my-plugin-select2-script');
            wp_enqueue_script('my-plugin-script');
        }
    }
    new BC_AJAX_Product_Search();
    

    2.Add your own js file called my_product_search_script.js next to the php file you are working in with this code:

    (function ($) {
        $(function(){
            $('.bc-product-search').select2({
                ajax: {
                    url: ajaxurl,
                    data: function (params) {
                        return {
                            term         : params.term,
                            action       : 'woocommerce_json_search_products_and_variations',
                            security: $(this).attr('data-security'),
                        };
                    },
                    processResults: function( data ) {
                        var terms = [];
                        if ( data ) {
                            $.each( data, function( id, text ) {
                                terms.push( { id: id, text: text } );
                            });
                        }
                        return {
                            results: terms
                        };
                    },
                    cache: true
                }
            });
        });
    })(jQuery)
    

    3.Finally, you can use in your php function this code which creates the products search select fields:

    <select data-security="<?php echo wp_create_nonce( 'search-products' ); ?>" multiple style="width: 300px;" class="bc-product-search"></select>
    

    3.1including presetting the field, and retrieving the value after form submition the select can be included in your php function like this:

    // use the selected product here
    if (isset($_POST["my_product_search"])) {
        $product_id = $_POST["my_product_search"];
        // TODO: do somthing with the product
    }
    ?>
    <form name='my_product_search_form' id='my_product_search_form' method='post' action='' class='my_product_search_form'>
        <p>
            <label for="my_product_search">Produkt:</label>
            <!-- here comes the select -->
            <select id="my_product_search" name="my_product_search" data-security="<?php echo wp_create_nonce( 'search-products' ); ?>" style="width: 300px;" class="bc-product-search"></select>
        </p>
        <input type='submit' class='button' name='save_products' value='Save' />
    
    </form>
    <script>
        <?php
            // here we preset the value, after saving
            if (isset($_POST["my_product_search"])) {
                $product_id = $_POST["my_product_search"];
                $product = wc_get_product($product_id);
        ?>
                jQuery(document).ready(function ($) {
                    var newOption = new Option("<?php echo $product->get_formatted_name() ?>", "<?php echo $product_id ?>", false, false);
                    $('#my_product_search').append(newOption).trigger('change');
                });
        <?php } ?>
    </script>
    <?php
    
  5. You are using woocommerce plugin. To filter the products with price range, color, size and other fields you can use another woocommerce plugin ‘woocommerce products filter’. You can user yith plugin to search the products. If you want to provide a search works for whole site not only for products only user dave’s live search plugin.

    Dave’s live search plugin

    Yith products search plugin

Comments are closed.