0

I have a custom post type and I also need a custom search. I want the post title and two custom fields to be indexed/queried. I found solutions for title only and for custom fields but not for both so I tried to combine. Why doesn't this work?

function custom_search( $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 ';
    }
    $searchand = ' OR ';
    foreach ( (array) $q['search_terms'] as $term ) {
        $term = esc_sql( like_escape( $term ) );
        $search .= "{$searchand}(($wpdb->m.meta_key = 'wpcf-kurzbeschreibung') AND (m.meta_value  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', 'custom_search', 500, 2 );

1 Answer 1

0

In my case I use a custom query so I can just use:

$query = new WP_Query(array('post_type' => 'akteur', 'meta_query' => array(
                                'relation' => 'OR',
                                array('key' => 'wpcf-kurzbeschreibung','compare' => 'LIKE','value' => $suchbegriff),
                                array('key' => 'wpcf-zusatzinfo','compare' => 'LIKE','value' => $suchbegriff)
                            )
                            ));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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