• Resolved Gald

    (@ager2014)


    Hello,

    When someone searches in my website, WP is retrieving all the information found in the posts (title, description), pages and also in a custom post type I have created, but just searches in the title and description. I would like also WordPress to search in the custom post fields named tamano and ano created by me.

    I’m using WPML for multilingualism, and plugins Advanced Custom Fields Pro and Custom Post Type UI, and custom post type is setup with Exclude from search = false.

    I would like to add the code that brings me also the post types that match with part of the term searched in the custom post type fields.

    I have tried different ways, but I think that this is the closest:

    add_action( ‘pre_get_posts’, ‘search_obra’ );
    function search_obra( $query )
    {
    echo $GLOBALS[‘wp_query’]->request;

    if (! $query->is_main_query()
    AND ” === $query->get( ‘s’ )
    AND ‘obra’ === $query->get( ‘post_type’ ))
    return $query;

    $query->set( ‘meta_query’, array(
    ‘relation’ => ‘OR’,
    array(
    ‘key’ => ‘ano’,
    ‘value’ => $query->get( ‘s’ ),
    ‘compare’ => ‘LIKE’
    ),
    array(
    ‘key’ => ‘tamano’,
    ‘value’ => $query->get( ‘s’ ),
    ‘compare’ => ‘LIKE’
    )
    ) );

    return $query;
    }

    The query that WP creates when I search by year (ano) 1966:

    SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts INNER JOIN wp_postmeta ON ( wp_posts.ID = wp_postmeta.post_id ) LEFT JOIN wp_icl_translations t ON wp_posts.ID = t.element_id AND t.element_type = CONCAT(‘post_’, wp_posts.post_type) WHERE 1=1 AND (((wp_posts.post_title LIKE ‘%1966%’) OR (wp_posts.post_content LIKE ‘%1966%’))) AND ( ( wp_postmeta.meta_key = ‘ano’ AND CAST(wp_postmeta.meta_value AS CHAR) LIKE ‘%1966%’ ) OR ( wp_postmeta.meta_key = ‘tamano’ AND CAST(wp_postmeta.meta_value AS CHAR) LIKE ‘%1966%’ ) ) AND wp_posts.post_type IN (‘post’, ‘page’, ‘attachment’, ‘obra’, ‘portfolio’) AND (wp_posts.post_status = ‘publish’ OR wp_posts.post_author = 1 AND wp_posts.post_status = ‘private’) AND ( ( t.language_code = ‘es’ AND wp_posts.post_type IN (‘post’,’page’,’attachment’,’acf-field-group’,’obra’ ) ) OR wp_posts.post_type NOT IN (‘post’,’page’,’attachment’,’acf-field-group’,’obra’ ) ) GROUP BY wp_posts.ID ORDER BY wp_posts.post_title LIKE ‘%1966%’ DESC, wp_posts.post_date DESC LIMIT 0, 10

    Thanks so much in advance!!!

Viewing 2 replies - 1 through 2 (of 2 total)
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Search also in custom post type fields’ is closed to new replies.