caleb
1/28/2017 - 2:39 AM

filter function to add postmeta field '_sections' to search

filter function to add postmeta field '_sections' to search

function posts_clauses( $clauses, $wp_query ) {
    /* reference: https://adambalee.com/search-wordpress-by-custom-fields-without-a-plugin/ */

    if ( !$wp_query->is_search() )
        return $clauses;

    global $wpdb;

    $clauses['join'] .= 
        ' LEFT JOIN ' . $wpdb->postmeta . 
            ' ON (' . 
                $wpdb->posts . '.ID = ' . $wpdb->postmeta . '.post_id ' . 
                'AND ' . $wpdb->postmeta . '.meta_key = "_sections"' . 
            ')';

    $clauses['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)",
        $clauses['where']
    );

    $clauses['distinct'] = "DISTINCT";

    return $clauses;

}