Forums › Forums › Search & Filter Pro › pre_get_posts adding condition to exclude search result page
Tagged: archive pre_get_posts
- This topic has 15 replies, 2 voices, and was last updated 5 years, 4 months ago by Trevor.
-
Anonymous(Private) July 8, 2019 at 4:18 pm #215737
Hello
I’m using a pre_get_posts function on my function.php page to add an offset to my query.
It works fine, but I want to exclude this function from my search results page.I’m using “as an archive” for display results method.
here is what my code looks like :
add_action('pre_get_posts', 'myprefix_query_offset', 1 ); function myprefix_query_offset(&$query) { if (is_front_page() && $query->is_main_query()){ // RUN CODE ONLY ON FRONT PAGE AND MAIN QUERY } else { return; } }
the problem is that my pre_get_posts is executed on my search results page, which is not normal, on my archives page the function is not executed which is fine…
How can I exclude this function from the search results ?
Can’t find a solution and It should work !
thanks
Trevor(Private) July 9, 2019 at 11:16 am #215764The ‘As an Archive’ method might cause that to happen
add_action('pre_get_posts', 'myprefix_query_offset', 1 ); function myprefix_query_offset(&$query) { if (is_front_page() && $query->is_main_query()){ global $searchandfilter; $sf_current_query = $searchandfilter->get(12345)->current_query(); if ((!$sf_current_query->is_filtered())&&($sf_current_query->get_search_term()=="")) { return; } else { // RUN CODE ONLY ON FRONT PAGE AND MAIN QUERY } } }
That might work. Change 12345 for the ID of your form.
Anonymous(Private) July 9, 2019 at 12:48 pm #215780thanks for your replay, but it’s not working… here is my full code, I don’t understand what’s wrong. search results page as an archive should behave like archive page. When I filter the category “cat_1” for example, I should get the same result as when I’m on the “cat_1” archive page, but its not the case, can you please let me know what’s wrong with my code ? thanks
add_action(‘pre_get_posts’, ‘myprefix_query_offset’, 1 );
function myprefix_query_offset(&$query) {
if(is_admin()) return;
if (is_home() && $query->is_main_query() && !is_archive()){
// This is my front Page
//First, define your desired offset…
$offset = 2;//Next, determine how many posts per page you want (we’ll use WordPress’s settings)
$ppp = get_option(‘posts_per_page’);//Next, detect and handle pagination…
if ( $query->is_paged ) {
//Manually determine page query offset (offset + current page (minus one) x posts per page)
$page_offset = $offset + ( ($query->query_vars[‘paged’] – 1) * $ppp );//Apply adjust page offset
$query->set(‘offset’, $page_offset );}
else {
//This is the first page. Just use the offset…
$query->set(‘offset’,$offset);}
} else {
return;
}
}
-
AuthorPosts