I’m trying to use is_search to output some stuff from functions.php. I’m using is_search on the actual search page itself and it works fine:
if(is_search()) {
echo get_search_query( '<h1>', '</h1>' );
}
But from functions.php this doesn’t work:
function data_scroll_all(){
if(is_search()) {
$offset = $_POST['offset'];
$category = $_POST['cat'];
$args = array('posts_per_page' => 3, 'category__not_in' => 1, 'offset' => $offset, 'orderby' => 'date', 'cat' => $category);
$loop = new WP_Query($args);
if($loop->have_posts()) {
while($loop->have_posts()){
$loop->the_post();
get_template_part( 'content-archive' );
}
} wp_reset_postdata();
} else {
echo "Nope!";
}
die('');
}
With this I just get “Nope!” when I’m on the search page.
I have my search template setup like this:
<?php
/*
Template Name: Search Page
*/
?>
<?php
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
$search = new WP_Query($search_query);
?>
I have a a waypoint “infinite-scroll” function that triggers when reaching the bottom of the page:
var ajax_url = $('.loadAll').attr('data-url');
var cat = $('.loadAll').attr('data-cat');
var offset = -3;
$('#infinite-load').waypoint(function (direction) {
if (direction === 'down') {
offset = parseInt(offset) + 3;
$.ajax({
dataType: "HTML",
url: ajax_url,
type: 'POST',
data: {
action: 'data_scroll_all',
cat: cat,
offset: offset
},
beforeSend: function () {
$(".loading").show(); //show image loading
},
success: function (data) {
$(".loading").hide();
$('#infinite-load').append(data);
$.waypoints('refresh');
}
});
}
}, {
offset: 'bottom-in-view'
});
An Ajax call is a new request to the server. The page that loads is (should be)
wp-admin/admin-ajax.php
which is template neutral. That is not a search page at all.is_search
won’t ever betrue
. Whatis_search
does, in short, is check the main query to see if you are on a search results template page. With an AJAX call toadmin-ajax.php
, you aren’t.You could probably just remove that check as presumably your function is only used where appropriate, but you’d need to provide more context for a solid answer.
Your code doesn’t show where you call data_scroll_all() from, so this is just a blind guess — apologies if it misses the mark.
It shouldn’t matter which .php fike the function is in, but is_search() can only be called from within The Loop — if the place your function is called from is outside the loop, it won’t work.
(It’s checking whether the current query is a search query, not whether or not you’re on a search page )