Support

Account

Home Forums General Issues meta_query not working and stopping all results Reply To: meta_query not working and stopping all results

  • Finally got this working and stable. A mixture of sources.
    Had a few issues with the fact I was creating an ajax search for a front end form.

    And them wanted to search more private fields in the admin using is_search && is_admin. The below is just for the ajax search. Set $GLOBALS[‘fd_search_term’] when the form data is posted.

    
    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', __NAMESPACE__ . '\\cf_search_join');
     
    function cf_search_where($where)
    {
        global $wpdb;
    
        // do not use !is_admin() as ajax returns this as true for ajax you can use :   !isset($GLOBALS['current_screen']) && !is_customize_preview() 
        if (!is_search() && $GLOBALS['fd_search_term']) {
    
            $s = $GLOBALS['fd_search_term'];
            // i have global array for each field to include.
            // To include all fields remove ' " . $wpdb->postmeta . ".meta_key IN ($imploded_fields) AND '
            $imploded_fields = implode(',', $GLOBALS['added_meta_field_to_search_query']);
    
            $where = preg_replace("/\(\s*" . $wpdb->posts . ".post_title\s+LIKE\s*(\'[^\']+\')\s*\)/",
                "(" . $wpdb->posts . ".post_title LIKE $1) OR (" . $wpdb->postmeta . ".meta_key IN ($imploded_fields) AND " . $wpdb->postmeta . ".meta_value LIKE $1)  ", $where);
        }
    
        return $where;
    }
    add_filter('posts_where', __NAMESPACE__ . '\\cf_search_where');
    
    function cf_search_distinct($where)
    {
        global $wpdb;
    
        if (!is_search()) {
            return "DISTINCT";
        }
    
        return $where;
    }
    add_filter('posts_distinct', __NAMESPACE__ . '\\cf_search_distinct');