I have a custom post type called event
. On the archive page I implemented a simple search which returns a selection of posts. Before submitting the search form I'm seeing the proper query vars for the archive page. Once I submit the search form those query vars are removed and return an empty string. I have a few conditionals depending on things like current_post and post_count. Can the ajax call re-populate those variables? How do I get those variables back?
<form id="siteSearchForm" action="<?= admin_url('admin-ajax.php') ?>" method="POST">
<input type="search" name="s" id="search" value="<?php the_search_query(); ?>" placeholder="Search Events" />
<input type="hidden" name="action" value="eventsFilter" />
<input type="submit" id="search-submit" alt="Search" value="Search" class="btn btn-white" />
</form>
The JS:
const searchFunctionality = ($) => {
$('#siteSearchForm').on('submit', function (e) {
e.preventDefault();
const search = $('#siteSearchForm');
$.ajax({
data: {
action: 'eventsFilter', // ajax function name
keyword: $('#search').val(), // search word
},
type: search.attr('method'),
url: search.attr('action'),
success: function (data) {
$('.events-wrapper').html(data);
},
});
return false;
});
};
and finally the AJAX php function:
<?php
add_action('wp_ajax_eventsFilter', 'events_filter');
add_action('wp_ajax_nopriv_eventsFilter', 'events_filter');
function events_filter()
{
$args = array( // match paramters found in pre_get_posts (/theme.php)
'meta_key' => 'event_start_date',
'order' => 'ASC',
'orderby' => 'meta_value',
'post_status' => 'publish',
'post_type' => 'event',
's' => $_POST["keyword"],
'tag__not_in' => array(16),
);
$query = new WP_Query($args);
if ($query->have_posts()) :
while ($query->have_posts()) : $query->the_post();
get_template_part('template-parts/content/content', 'archive');
endwhile;
wp_reset_postdata();
else :
echo 'No posts found';
endif;
die();
}
.events-wrapper
with the AJAX response. It’s not replacing any variables. AJAX can’t do that. If you have logic in your archive template inside the wrapper then that logic would also need to be in the AJAX handler if you’re replacing it.post_count
, after the AJAX response that's gone. I don't think ajax is able to inject things into the PHP variables of WordPress (happy to be wrong here)post_count
query var is being replaced?