Include woocommerce custom field value in front-end search result

admin2025-01-07  4

currently the search result only showing all the woocommerce default product field (product title, category, tag, .etc).

I've add a new custom field inside the woocommerce product using this code inside functions.php

/** Add Sub-Title option in Woocommerce */

add_action( 'woocommerce_product_options_general_product_data', 'my_custom_field' );

function my_custom_field() {

woocommerce_wp_text_input( 
array( 
    'id'          => '_subtitle', 
    'label'       => __( 'Reference', 'woocommerce' ), 
    'placeholder' => 'Reference code',
    'description' => __( 'Enter the reference code', 'woocommerce' ) 
)
);

}

add_action( 'woocommerce_process_product_meta', 'my_custom_field_save' );

function my_custom_field_save( $post_id ){  

$subtitle = $_POST['_subtitle'];
if( !empty( $subtitle ) )
    update_post_meta( $post_id, '_subtitle', esc_attr( $subtitle ) );

}

How can I include this custom field value in the search result? I've tried google for it, but no any significant solution.

currently the search result only showing all the woocommerce default product field (product title, category, tag, .etc).

I've add a new custom field inside the woocommerce product using this code inside functions.php

/** Add Sub-Title option in Woocommerce */

add_action( 'woocommerce_product_options_general_product_data', 'my_custom_field' );

function my_custom_field() {

woocommerce_wp_text_input( 
array( 
    'id'          => '_subtitle', 
    'label'       => __( 'Reference', 'woocommerce' ), 
    'placeholder' => 'Reference code',
    'description' => __( 'Enter the reference code', 'woocommerce' ) 
)
);

}

add_action( 'woocommerce_process_product_meta', 'my_custom_field_save' );

function my_custom_field_save( $post_id ){  

$subtitle = $_POST['_subtitle'];
if( !empty( $subtitle ) )
    update_post_meta( $post_id, '_subtitle', esc_attr( $subtitle ) );

}

How can I include this custom field value in the search result? I've tried google for it, but no any significant solution.

Share Improve this question asked Nov 2, 2018 at 4:15 iceiceicyiceiceicy 1398 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

You have to modify WooCommerce search query.

  1. Hook into this action: do_action( 'woocommerce_product_query', $query, $instance );
  2. Detect if it is a search query
  3. Add your _subtitle meta

Something like this (not tested):

if ( $query->is_search ) {
    $query->set('meta_query', array(
        array(
            'key' => '_subtitle',
            'value' => $query->query_vars['s'],
            'compare' => 'LIKE'
        )
    ));
};
转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1736262216a801.html

最新回复(0)