0

I'm using the standard WordPress search form to search a custom post type. Here is my code:

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

I would like to limit this to ONLY search the post title. Is there a way to do that? Thank you.

2
  • 1
    Did you read this?
    – tfrommen
    Commented Apr 18, 2013 at 21:24
  • I did. However, that seems to be a global control for search. I don't want my general site search to be limited, only for the custom post type. Is it possible to use that or something else to limit it only to the custom post type?
    – Shawn
    Commented Apr 19, 2013 at 0:24

2 Answers 2

2

I didn't test the code below, but I guess it works.

/**
 * Search SQL filter for matching against post title only.
 */
function __search_by_title_only( $search, &$wp_query )
{
     /*my solution */
     if($_GET['post_type'] != 'attorney' )
        return $search;
     /*my solution*/


     //please copy the rest of the code from the link below
}
add_filter( 'posts_search', '__search_by_title_only', 500, 2 );

how to limit search to post titles?

1
  • @Shawn, looks like the question can be closed now right? Please mark the answer as "accepted". Commented Jul 12, 2013 at 7:57
1

add this code to funtions.php;

// Search by Post Title
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 );

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