0

Limiting post search to titles only is a breeze, but WooCommerce's post types don't abide by this rule. I have tried modifying the code below to be specific to products but am not having any luck.

function search_by_title_only( $search, &$wp_query )
{
    global $wpdb;
    if ( empty( $search ) )
        return $search; // skip processing - no search term in query
    $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 );

I'm not sure if I'm not using the right hooks or if I'm barking up the wrong tree altogether. Anyone know how to do this?

0

It turns out the free Relevanssi plugin does this rather well. I was afraid it would only search posts and not custom post types, but it does it all... and rather well! It only requires a simple filter added to your theme's functions.php file to get it to omit the body content:

// search titles only (relevanssi plugin)
add_filter('relevanssi_index_content', 'contentoff');
function contentoff() {
    return false;
}

alternatively you can have it omit titles (don't use the two together or you'll be searching nothing!

// search titles only (relevanssi plugin)
add_filter('relevanssi_index_titles', 'contentoff');
function contentoff() {
    return false;
}
  • ...and there's the added bonus of it returning search results by relevance instead of by date or name. – kristina childs May 9 '13 at 17:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.