0

I have 2 postmeta english_title and english_content for each post. When user search something, plus post tile and post content, I need it search on this two meta keys too. I use this function

function custom_search_query( $query ) {
    // Ensure it is a search query and the main query
    if ( $query->is_search() && $query->is_main_query() ) {
        // Get the search term
        $search_terms = $query->query_vars['s'];

        // Add meta query for searching custom fields
        $meta_query = [
            'relation' => 'OR',
            [
                'key'     => 'english_title',
                'value'   => '%' . $search_terms . '%',
                'compare' => 'LIKE',
            ],
            [
                'key'     => 'english_content',
                'value'   => '%' . $search_terms . '%',
                'compare' => 'LIKE',
            ],
        ];

        // Set the meta query for custom fields
        $query->set( 'meta_query', $meta_query );
    }
}

add_action( 'pre_get_posts', 'custom_search_query' );

I am using them by default with no plugin, but when I use this function, nothing shows up, even if the keyword is in the post title. there is nothing on the debug file.

could you tell me how can debug it to solve the problem

1 Answer 1

0

For WP_Query(), you don't need to add the % before and after the keyword when using LIKE as comparison. WP_Query() will handle it for you. If you add %, WP_Query() thinks that you want to add that character itself to the search. That's the first reason you don't see any results.

The second problem is that if you have the query as above, the $search_term need to match (post title OR post content) AND (meta field english_title OR english_content).

You can use $wpdb() to search instead of WP_Query() because sometimes WP_Query() is limited for customisation like that.

Please follow the tutorial given here: https://adambalee.com/search-wordpress-by-custom-fields-without-a-plugin/

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.