So I think I might be doing something fundamentally wrong in my WordPress themes since this issue seems to crop up every once in a while and I don’t know why.
So basically I created search.php and I use relevanssi to sort my search results by relevancy. When I search for “camera” and do echo get_post_type();
I get “reviews” but if I search for “test” and do echo get_post_type();
I get “articles”.
I tried injecting wp_reset_query() just about everywhere to try and see if I was changing it randomly but it’s not that. I think WP is confused since my search result page isn’t really linked with any specific page so it is not set to a specific post type. Is there a way to have it be a page?
Any help is appreciated
edit:
I added the code below. In the var_dump I just see the query stuff but get_post_type() is different on every search term.
search.php:
<?php
get_header();
global $query_string;
$query_args = explode("&", $query_string);
$search_query = array();
foreach($query_args as $key => $string) {
$query_split = explode("=", $string);
$search_query[$query_split[0]] = urldecode($query_split[1]);
} // foreach
$args = array(
'posts_per_page' => get_option('posts_per_page'),
's' => $search_query['s']
);
echo get_post_type() .'<br>';
var_dump($args);
$search = new WP_Query($args);
if( $search->have_posts() ) {
while( $search->have_posts() ) {
$search->the_post();
include( get_template_directory() . '/includes/templates/search_result.inc.php' );
}
wp_reset_query();
}
?>
<a id="ld-more" href="#search">Load more search results</a>
<?php
get_footer();
Your problem is almost certainly that you’ve created a second query. That query is going to be out of sync with the main query, hence you are getting unexpected results.
From what I can see, you aren’t really doing anything that the main query doesn’t already do, so I think you really only need the Loop itself.