Home Forums Themes Support WooCommerce search Product by title only in WordPress

  • This topic is empty.
Viewing 1 post (of 1 total)
  • Author
    Posts
  • #11875

    Hi all customer,

    In this topic tutorial we’ll help you customize to search Product by title only in WooCommerce WordPress.

    1. Custom search result in the search page: by default WordPress will search in title, content,… like this:

    Example: https://teespace.harutheme.com/?s=t%20shirt&post_type=product

    For search by title only please go to wp-content/themes/xxx/functions.php (xxx is theme folder) then add this code:

    if ( ! function_exists( 'haru_search_by_title' ) ) {
    function haru_search_by_title( $search, $wp_query ) {
    if ( ! empty( $search ) && ! empty( $wp_query->query_vars['search_terms'] ) ) {
    global $wpdb;
    
    $q = $wp_query->query_vars;
    $n = ! empty( $q['exact'] ) ? '' : '%';
    
    $search = array();
    
    foreach ( ( array ) $q['search_terms'] as $term )
    $search[] = $wpdb->prepare( "$wpdb->posts.post_title LIKE %s", $n . $wpdb->esc_like( $term ) . $n );
    
    if ( ! is_user_logged_in() )
    $search[] = "$wpdb->posts.post_password = ''";
    
    $search = ' AND ' . implode( ' AND ', $search );
    }
    
    return $search;
    }
    
    add_filter( 'posts_search', 'haru_search_by_title', 10, 2 );
    }

    2. Custom search result in the WP_Query

    Some widgets or shortcode will use WP_Query for the search result.

    Example: in our plugin for search ajax result in: wp-content/plugins/haru-xxx/includes/classes/product-ajax-actions.php (haru-xxx is our plugin folder)

    Add the code before & after WP_Query like this:

    add_filter( 'posts_where', 'haru_title_filter', 10, 2 );
    $search = new WP_Query( $search_query );
    remove_filter( 'posts_where', 'haru_title_filter', 10, 2 );

    Add this function in product-ajax-actions.php or functions.php

    function haru_title_filter( $where, &$wp_query ){
    global $wpdb;
    if ( $search_term = $wp_query->get( 'search_prod_title' ) ) {
    $where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( $wpdb->esc_like( $search_term ) ) . '%\'';
    }
    return $where;
    }

    Hope this helps and thanks for reading!

    ****
    Regards,

    HaruTheme

    • This topic was modified 1 month, 2 weeks ago by admin.
    • This topic was modified 1 month, 2 weeks ago by admin.
Viewing 1 post (of 1 total)

You must be logged in to reply to this topic.