Skip to main content
2 of 3
added 44 characters in body
kaiser
  • 50.8k
  • 27
  • 150
  • 244

WooCommerce product search titles only

I had asked this earlier and solved it using the Relevanssi plugin, however that plugin is now breaking things so I can't use it anymore. How is something so freaking simple made so impossible by woocommerce?? AAARG!

I tried using this solution, but it didn't seem to work for me. I've also tried searching out the woocommerce product_search function and adding a filter to that, but didn't get anywhere with it, either.

Here's the last thing I tried, which still returned search results from all content, not just titles:

MarkUp

<form role="search" method="get" id="searchform" action="<?php echo home_url( '/' ); ?>">
    <input type="hidden" name="post_type" value="product" />
    <input type="text" value="" name="s" />
    <input type="submit" value="Search" />
</form> 

Search-SQL filter callback

// Search product titles only.
function __search_by_title_only( $search, &$wp_query ) {
    global $wpdb;
    if($_GET['post_type'] = 'product' )
        return $search;
    $q = $wp_query->query_vars;
    $n = ! empty( $q['exact'] ) ? '' : '%';
    $search =
    $searchand = '';
    foreach ( (array) $q['search_terms'] as $term ) {
        $term = esc_sql( like_escape( $term ) );
        $search .= "{$searchand}($wpdb->posts.post_title LIKE '{$n}{$term}{$n}')";
        $searchand = ' AND ';
    }
    if ( ! empty( $search ) ) {
        $search = " AND ({$search}) ";
        if ( ! is_user_logged_in() )
            $search .= " AND ($wpdb->posts.post_password = '') ";
    }
    return $search;
}
add_filter( 'posts_search', '__search_by_title_only', 500, 2 );

Anyone? I imagine it has something to do with the woocommerce post type itself... they like to put in a lot of custom hooks and such.