• Resolved jllrh

    (@jllrh)


    We have built a page at search.php that uses a custom WP_Query, with relevanssi set to true.

    Setup below:

    global $wp_query;
    global $query_string;

    $query_args = explode("&", $query_string);
    $search_query = array();

    // Get ?s= term
    if($query_args[0]) {
    foreach($query_args as $key => $string) {
    $query_split = explode("=", $string);
    $search_query[$query_split[0]] = $query_split[1];
    }
    }

    // URL urldecode term to allow spaces
    if(!empty($search_query['s'])) {
    $search_query['s'] = urldecode($search_query['s']);
    }

    // Disable pagination for now
    $search_query['nopaging'] = true;

    // use Relevanssi plugin for search
    $search_query['relevanssi'] = true;

    // Post types
    $search_post_types = array('projects', 'post', 'people', 'research', 'event');
    $search_query['post_type'] = $search_post_types;

    $search = new WP_Query($search_query);
    $total_results = $search->post_count;

    We then loop over $search and it all seems to work fine, but it also seems like the query is being fired twice.

    Every time we test a search entry, it is logged twice in the user search admin area. Screenshots attached at the end.

    How can we make it so the query only submits once from this default search page.

    Cheers.
    J

Viewing 2 replies - 1 through 2 (of 2 total)
  • Plugin Author Mikko Saari

    (@msaari)

    You’ve explicitly set up your WordPress to run each search twice, so that’s what happens. There’s the default WP_Query, then you discard that and run a new one.

    In general, you want to modify the existing WP_Query instead of discarding it and running a new one. Remove the WP_Query code from the search results template, and instead add a function to the relevanssi_modify_wp_query hook to adjust the main WP_Query to your liking. This will give you many benefits: your template code is cleaner, you won’t get duplicate search log entries and your searches will be twice as fast as you’re only doing one search, not two.

    So, move all that WP_Query logic to a function hooked to the relevanssi_modify_wp_query to set the query parameters to your liking, but don’t run the query: let WP do that for you. That’s much easier than disabling the main WP_Query, which would be the other option.

    Thread Starter jllrh

    (@jllrh)

    Ah I see, thank you! This is a great help.

Viewing 2 replies - 1 through 2 (of 2 total)

You must be logged in to reply to this topic.