0

I've set up a custom post type (People) that outputs WordPress user content on it's single page.

In brief, the way it works is when adding a new post, you give it a user ID and the post will populate the page based on this users info. (Name, E-mail, Description, Other Custom Fields etc).

I've added custom ACF WYSIWG fields to the user, which are all populated with content, yet when searching for words which are included in these fields, it doesn't return the post. Only when searching for the name of the post, it returns the post.

Presumably, User Fields are not included in the default WordPress search, is there a way where i can include User fields to be searchable so that the desired post will appear in the search results?

1 Answers1

2

You are "User fields" mentioned. But here I think it adds "Post fields". Because add an "user data" on the "post data" does not make it a "user fields". It still a post fields.

Wrapping It Up

Add the following to functions.php to start searching WordPress by custom fields. Not only will this code modify the search on the front-end, but you’ll also be able to search the edit screens in the admin by custom fields as well.

<?php
/**
 * Extend WordPress search to include custom fields
 *
 * https://adambalee.com
 */

/**
 * Join posts and postmeta tables
 *
 * http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_join
 */
function cf_search_join( $join ) {
    global $wpdb;

    if ( is_search() ) {    
        $join .=' LEFT JOIN '.$wpdb->postmeta. ' ON '. $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ';
    }

    return $join;
}
add_filter('posts_join', 'cf_search_join' );

/**
 * Modify the search query with posts_where
 *
 * http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_where
 */
function cf_search_where( $where ) {
    global $pagenow, $wpdb;

    if ( is_search() ) {
        $where = preg_replace(
            "/\(\s*".$wpdb->posts.".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
            "(".$wpdb->posts.".post_title LIKE $1) OR (".$wpdb->postmeta.".meta_value LIKE $1)", $where );
    }

    return $where;
}
add_filter( 'posts_where', 'cf_search_where' );

/**
 * Prevent duplicates
 *
 * http://codex.wordpress.org/Plugin_API/Filter_Reference/posts_distinct
 */
function cf_search_distinct( $where ) {
    global $wpdb;

    if ( is_search() ) {
        return "DISTINCT";
    }

    return $where;
}
add_filter( 'posts_distinct', 'cf_search_distinct' );

Note: if you have some "post meta"s that you have not included in the article and have not shown at the front end. This will call by them!

Quotation: Search WordPress by Custom Fields without a Plugin

BOZ
  • 2,731
  • 11
  • 28