1

I am endeavouring to have wordpress search in one custom field, and no other post text or attributes. The site has a very specific function which is to return posts having an exact match on the first letter(s) of a UK postcode in a custom field. No other searching is required.

So each post represents an engineering company which has a number of UK postcodes set against it. When the site user searches for a specific postcode it should return all posts with that code present.

I am using the Advanced Custom Fields Plugin

I have tried this code in my child theme functions.php

function __search_by_postcode_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.search_post_code 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_postcode_only', 500, 2 );

Where search_post_code is the custom field in question which can have multiple values.

I have tried other enhanced search plugins but they all seem to search Post Title and Post Content as well.

Any help appreciated.

Thanks

-1

On WordPress you can filter searches when accessing the URL with an additional parameter on the end for example;

https://www.your-website.com/?s=search-query&post_type=custom_post_type_name

If you are accessing this URL from a search box / form on your website, add in the following hidden field;

<input type="hidden" name="post_type" value="post type name" />
  • The OP wants to query a custom field. They aren't accessible just by adding a query string. To the URL. – Andy Macaulay-Brook Aug 15 '16 at 20:54

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.