How to execute two actions with one ajax call - WordPress - javascript

I have a section for "tours" in my page.
The tours have 2 filters (select inputs). "destino" and "duracion" (location and duration)
So far I made one of the filter work with ajax, and update the "#result" id with the new tours once you select a "destino".
But i also want to update the "duracion" select with the new options (based on the destino selected).
Problem is, i have no idea how to execute two actions and have the response on two different places.
Html part: (here I have both actions, its only executing the last one)
<form class="filtros righter" action="**********/wp-admin/admin-ajax.php" method="POST" id="filtro">
<input type="hidden" name="action" value="filtertoursajax">
<input type="hidden" name="action" value="filterduracionajax">
<input type="hidden" name="filtrodestino" value="salar-de-uyuni">
<div class="select-holder">
<label class="">Categoría</label>
<select name="categoriafilter" id="categoriafilter">
<option disabled="" selected="" value="0"> </option>
<option value="0">Todas las categorías</option>
<option value="11">Clásicos</option>
<option value="33">Elite</option>
</select>
</div>
<div class="select-holder">
<label>Duración del viaje</label>
<select name="duracionfilter" id="resultselect">
<option disabled="" selected="" value="0"> </option>
<option value="0">Todas las duraciones</option>
</select>
</div>
</form>
Js part:
<script>
jQuery(function myFunction(){
$('#filtro').change(function(){
var filter = $('#filtro');
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
beforeSend:function(xhr, data){
filter.find('button').text('Processing...'); // changing the button label
},
success:function(data){
filter.find('button').text('Apply filter'); // changing the button label back
$('#response').html(data); // insert data
console.log(data);
},
error: function(req, err){ console.log(err);
}
});
return false;
});
});
PHP action 1:
add_action('wp_ajax_filtertoursajax', 'filtertoursajax');
add_action('wp_ajax_nopriv_filtertoursajax', 'filtertoursajax');
function filtertoursajax(){
$args = array(
'post_type' => 'tours',
'orderby' => 'menu_order',
'order' => 'ASC',
'post_per_page' => -1,
);
if( isset($_POST['filtrodestino']) && $_POST['filtrodestino'] ) {
// for taxonomies / categoria
if( isset( $_POST['filtrodestino'] ) ) {
$args['tax_query'][] =
array(
'taxonomy' => 'destino',
'field' => 'slug',
'terms' => $_POST['filtrodestino']
);
}
}
if( isset($_POST['categoriafilter']) && $_POST['categoriafilter'] ) {
// for taxonomies / categoria
$args['tax_query'][] =
array(
'taxonomy' => 'categoria',
'field' => 'id',
'terms' => $_POST['categoriafilter']
);
}
$query = new WP_Query( $args );
if( $query->have_posts() ) :
print_r($args);
while( $query->have_posts() ): $query->the_post();
$postid = $query->post->ID;
$taxonomy = 'destino';
$terms = get_the_terms( get_the_ID(), $taxonomy );
if ( $terms && ! is_wp_error( $terms ) ) :
$term_links = array();
foreach ( $terms as $term ) {
$term_links[] = '' . __( $term->name ) . '';
}
$all_terms = join( ', ', $term_links );
$destinos = '<span class="terms-' . esc_attr( $term->slug ) . '">' . __( $all_terms ) . '</span>';
endif;
?>
<div class="box">
<div class="box__image flexer">
<?php echo wp_get_attachment_image( get_field( "foto_portada", $postid ), array('276', '180'), "", array( "class" => "img-responsive" ) ); ?>
</div>
<div class="box__content pz-1">
<span class="placeholder mb-1"><?php echo $destinos; ?></span>
<h6 class="long-title mb-2"><?php echo $query->post->post_title; ?></h6>
<div class="icon-btn"><?php $path = get_template_directory_uri().'/images/plane-icon.svg'; echo file_get_contents($path); ?>Duración: <?php echo get_field( "duracion_texto", $postid ); ?></div>
</div>
Ver ficha<?php $path = get_template_directory_uri().'/images/arrow-btn.svg'; echo file_get_contents($path); ?>
</div>
<?php endwhile;
wp_reset_postdata();
else:
echo 'Sin resultados';
print_r($args);
endif;
die();
}
PHP action 2:
add_action('wp_ajax_filterduracionajax', 'filterduracionajax'); //
add_action('wp_ajax_nopriv_filterduracionajax', 'filterduracionajax');
function filterduracionajax(){
if( $args = array(
'posts_per_page' => -1,
'hide_empty' => 1,
'post_type' => 'tours',
'meta_key' => 'dias',
'orderby' => 'meta_value',
'order' => 'ASC',
) ) :
// create $args['tax_query'] array if one of the following fields is filled
if( isset($_POST['filtrodestino']) && $_POST['filtrodestino'] ) {
// for taxonomies / categoria
if( isset( $_POST['filtrodestino'] ) ) {
$args['tax_query'][] =
array(
'taxonomy' => 'destino',
'field' => 'slug',
'terms' => $_POST['filtrodestino']
);
}
}
// create $args['tax_query'] array if one of the following fields is filled
if( isset($_POST['categoriafilter']) && $_POST['categoriafilter'] ) {
// for taxonomies / categoria
$args['tax_query'][] =
array(
'taxonomy' => 'categoria',
'field' => 'id',
'terms' => $_POST['categoriafilter']
);
}
// query
$the_query = new WP_Query( $args );
if( $the_query->have_posts() ): ?>
<div class="select-holder">
<label>Duración del viaje</label>
<select name="duracionfilter" id="resultselect">
<option disabled="" selected="" value="0"> </option>
<option value="0" >Todas las duraciones</option>
<?php $unique_dias = array();
while( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php $dias = get_field('dias');
if( ! in_array( $dias, $unique_dias ) ) :
$unique_dias[] = $dias; ?>
<?php endif;
endwhile;
natsort($unique_dias);
foreach ( $unique_dias as $duraciones ) :
echo '<option value="'.$duraciones.'">'.$duraciones.'</option>';
endforeach;
?>
</select></div>
<?php endif;
endif;
die();
}
Im very new with Ajax, this code is made by pieces of tutorials i found. The code is mostly made following this tutorial: https://rudrastyh.com/wordpress/ajax-post-filters.html
I just need both php actions to execute on "form" change and update the "tours" on #response div and also update the select input with #resultselect id.
Thanks!
Thanks to #lewis4you I'm able to get the data on the 2 divs at the same time. But i fail to understand how to execute both actions at the same time, but with different actions from functions.php
This
add_action('wp_ajax_filterduracionajax', 'filterduracionajax'); //
add_action('wp_ajax_nopriv_filterduracionajax', 'filterduracionajax');
has to return data to #resultselect
and
add_action('wp_ajax_filtertoursajax', 'filtertoursajax');
add_action('wp_ajax_nopriv_filtertoursajax', 'filtertoursajax');
has to return data to #response div
My main problem is that i dont know how to select the action i want to execute in
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
type:filter.attr('method'), // POST

I didn't read the question fully but I think you want something like this:
$('#filtro').change(function() {
var filter = $('#filtro');
ajax1(filter);
ajax2(filter);
});
function ajax1(filter) {
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
// ... further code
}
function ajax2(filter) {
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
// ... further code
}
The scenario where you send the data to the same controller from one $.ajax call:
$('#filtro').change(function() {
var filter = $('#filtro');
ajax1(filter);
});
in controller you have to store the data into array with keys so you can access it later in ajax success() function
public function someFunction($dataFromAjax) {
// do something with $dataFromAjax
$dataForDivs = [
'div1' => 'some data',
'div2' => 'some data2'
];
return $dataForDivs;
}
then in your $ajax in success:function(data) you can access that data with
success:function(data) {
let div1Data = data.responseJSON.div1;
let div2Data = data.responseJSON.div2;
filter.find('button').text(div1Data); // changing the button label back
$('#response').html(div2Data); // insert data
console.log(div1Data, div2Data);
},

Have you thought of using JS's Fetch API instead of jQuery's Ajax? Fetch returns a promise then it can execute a chain of .then() blocks where you can put another fetch() to your PHP url.
See an example here:
using a fetch inside another fetch in javascript

Related

How to split AJAX response into two divs

How I could get AJAX response splitted in two separate divs?
Situation: I have custom post type (case-studies) filter by custom taxonomy(case study category). On page load I query by exact category. But when I filter it by category I want to get AJAX response divided into two parts. First one even posts appears in filtered-post-top div and odd posts appears in filtered-post-bottom div.
Here is what I have achieved so far.
functionts.php file:
function filter_ajax() {
$category = $_POST['category'];
$args = array(
'post_type' => 'case-studies',
'posts_per_page' => 4,
'tax_query' => array(
array(
'taxonomy' => 'case_study_categories',
'terms' => $category
)
)
);
$query = new WP_Query($args);
if($query->have_posts()) :
while($query->have_posts()) : $query->the_post();
get_template_part( 'partials/case-studies-archive-post' );
endwhile;
endif;
wp_reset_postdata();
die();
}
ajaxRequest.js
$(document).ready(function () {
$('.filter-item > span').on('click', function(e) {
e.preventDefault();
var category = $(this).data('category');
console.log(category);
data = {
'action': 'filter',
'category': category
};
$.ajax({
url : wp_ajax.ajax_url,
data : data,
type : 'post',
success: function(result) {
$('.filtered-posts').html(result);
console.log(result);
},
error: function(result) {
console.warn(result);
}
});
})
});
Archive-case-studies.php
<section>
<div class="filtered-posts-top">
<?php
$args = array(
'post_type' => 'case-studies',
'posts_per_page' => 4,
'tax_query' => array(
array(
'taxonomy' => 'case_study_categories',
'terms' => 14
)
)
);
$counter = 0;
$query = new WP_Query($args);
if ($query->have_posts()) :
while ( $query->have_posts()) : $query->the_post();
$counter++;
if( $counter % 2 == 0 ) :
get_template_part( 'partials/case-studies-archive-post' );
endif;
endwhile;
endif;
wp_reset_postdata(); ?>
</div>
<div class="case-studies-categories">
<?php
$args = array(
'taxonomy' => 'case_study_categories'
);
$categories = get_terms( $args );
?>
<?php foreach ( $categories as $cat ) :?>
<div class="filter-item">
<span data-category="<?php echo $cat->term_id;?>"><?php echo $cat->name; ?></span>
</div>
<?php endforeach; ?>
</div>
<div class="filtered-posts-bottom">
<?php
$args = array(
'post_type' => 'case-studies',
'posts_per_page' => 4,
'tax_query' => array(
array(
'taxonomy' => 'case_study_categories',
'terms' => 14
)
)
);
$counter = 0;
$query = new WP_Query($args);
if ($query->have_posts()) :
while ( $query->have_posts()) : $query->the_post();
$counter++;
if( $counter % 2 == 1 ) :
get_template_part( 'partials/case-studies-archive-post' );
endif;
endwhile;
endif;
wp_reset_postdata(); ?>
</div>
</section>
Maybe someone will have idea how to solve the issue.

Display WordPress search results based on the selected Sub-Category

I'm trying to create a search using dropdowns in WordPress.
I've got two dropdowns, 1 - Parent Category and 1 - Sub-category.
The Sub-category will show automatically based on the selected Parent category.
My goal is to have the 2 dropdowns with a submit button and have it act as a search, displaying the selected sub-category's posts on the results page.
I've got this far using research but I'm completely lost and struggling as you can see.
Below is my functions.php code used for the search:
// FUNCTIONS.PHP
// Drop-down Ajax call
add_action('wp_ajax_my_special_action', 'my_action_callback');
add_action('wp_ajax_nopriv_my_special_action', 'my_action_callback');
function my_action_callback() {
if(isset($_POST['main_catid'])) {
$categories = get_categories('child_of='.$_POST['main_catid'].'&hide_empty=0');
foreach ($categories as $cat) {
$option .= '<option value="'.$cat->term_id.'">';
$option .= $cat->cat_name;
$option .= ' ('.$cat->category_count.')';
$option .= '</option>';
}
echo '<option value="-1" selected="selected">Search...</option>'.$option;
die();
} // end if
}
// Define search for sub-category
function search_filter( $query ) {
// only modify your custom search query.
if ( $query->is_search && $_post['my_search'] == "c_search") {
$args = array(
'relation' => 'AND',
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => array( $_post['main_cat']),
'operator' => 'IN'
),
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => array( $_post['sub_cat']),
'operator' => 'IN'
)
);
$query->set( 'tax_query', $args);
}
return $query;
}
// The hook needed to search_filter
add_filter( 'the_search_query','search_filter');
This is the HTML & JS code used for the form and Ajax call for the sub-categories:
<!-- BODY HTML CODE -->
<div id="content">
<!-- Search form-->
<form method="get" id="searchform" action="<?php bloginfo('url'); ?>/">
<div>
<input type="text" value="<?php the_search_query(); ?>" name="s" id="s" />
<?php
wp_dropdown_categories('show_count=0&selected=-1&hierarchical=1&depth=1&hide_empty=0&exclude=1&show_option_none=Main Categories&name=main_cat');
?>
<select name="sub_cat" id="sub_cat" enabled="disabled"></select>
<input type="hidden" id="my_search" name="my_search" value="c_search" />
<input type="submit" id="searchsubmit" value="search" />
</div>
</form>
<!-- Dropdown Ajax call script -->
<script type="text/javascript">
jQuery(function() {
jQuery('#main_cat').change(function() {
var $mainCat = jQuery('#main_cat').val();
// call ajax
jQuery("#sub_cat").empty();
jQuery.ajax({
url: "wp-admin/admin-ajax.php",
type: 'POST',
data: 'action=my_special_action&main_catid=' + $mainCat,
success: function(results) {
// alert(results);
jQuery("#sub_cat").removeAttr("disabled");
jQuery("#sub_cat").append(results);
}
});
});
});
</script>
</div>
the_search_query filter is not for that purpose. Use pre_get_posts filter instead.
Try this code:
// Define search for sub-category
function search_filter( $query ) {
// only modify your custom search query.
if ( $query->is_search && !is_admin() && $_post['my_search'] == "c_search" ) {
$args = array(
'relation' => 'AND',
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => array( $_post['main_cat']),
'operator' => 'IN'
),
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => array( $_post['sub_cat']),
'operator' => 'IN'
)
);
$query->set( 'tax_query', $args);
}
return $query;
}
add_filter( 'pre_get_posts', 'search_filter' );

jquery and styles not working when requested with ajax

I have FAQ Page where I am showing FAQs based on category. When I load the page first time, FAQ slide up and slide down is working fine, but when I click on others tabs for category search, then those FAQs are shown up, but no js and css is working.
Here is my FAQ page code:
<div class="faq-ajax-wrapper">
<ul class="accordion-list">
<?php
$faq_count = 1;
$args = array(
'post_type' => 'faq',
'posts_per_page' => -1,
'orderby' => 'date',
'order' => 'desc',
);
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
?>
<li>
<h3><span class="bullet"><?php echo $faq_count++; ?></span> <?php the_title(); ?></h3>
<div class="answer">
<?php the_content(); ?>
</div>
</li>
<?php } } wp_reset_postdata(); ?>
</ul>
</div>
JS code for the FAQ
<script>
jQuery(document).ready(function(){
jQuery('.accordion-list > li > .answer').hide();
jQuery('.accordion-list > li').click(function() {
alert('test');
if (jQuery(this).hasClass("active")) {
jQuery(this).removeClass("active").find(".answer").slideUp();
} else {
jQuery(".accordion-list > li.active .answer").slideUp();
jQuery(".accordion-list > li.active").removeClass("active");
jQuery(this).addClass("active").find(".answer").slideDown();
}
// return false;
});
});
</script>
Here is my AJAX code
jQuery(".faq-tabs .faq-filter").on("click", function(){
jQuery('.faq-tabs .faq-filter.active').removeClass('active');
jQuery(this).addClass('active');
faqHandler();
});
jQuery.fn.keyupDelay = function( cb, delay ){
if(delay == null){
delay = 400;
}
var timer = 0;
return $(this).on('keyup',function(){
clearTimeout(timer);
timer = setTimeout( cb , delay );
});
}
jQuery("#faq-search").keyupDelay( faqHandler );
function faqHandler() {
var faq_tabs = $( '.faq-tabs .faq-filter.active' ).data("category-id");
var faq_search = $( '#faq-search' ).val();
faqdata = {
'action': 'filter_faqs',
'faq_tabs': faq_tabs,
'faq_search': faq_search
};
jQuery.ajax({
url : blog.ajaxurl,
data : faqdata,
type : 'POST',
beforeSend : function ( xhr ) {
$('.faq-loader').css( 'display', 'block' );
},
success : function( faqdata ) {
if ( faqdata ) {
$('.faq-loader').css( 'display', 'none' );
$('.faq-ajax-wrapper').html( faqdata.faqposts );
} else {
$('.faq-loader').css( 'display', 'none' );
$('.faq-ajax-wrapper').html( 'No posts found.' );
}
}
});
}
function ajax_filter_faqs_handler() {
$faq_category = esc_attr( $_POST['faq_tabs'] );
$faq_search = esc_attr( $_POST['faq_search'] );
$faq_args = array(
'post_type' => 'faq',
'post_status' => 'publish',
'posts_per_page' => -1,
'orderby' => 'date',
'order' => 'DESC',
);
if ( $faq_category != 'all' ) {
$faq_args['tax_query'] = array(
array(
'taxonomy' => 'faq_category',
'field' => 'id',
'terms' => $faq_category,
),
);
}
if ( $faq_search != '' ) {
$faq_args['s'] = $faq_search;
}
$faqposts = 'No posts found.';
$faq_count = 1;
$faq_query = new WP_Query( $faq_args );
if ( $faq_query->have_posts() ) :
ob_start(); ?>
<ul class="accordion-list">
<?php while ( $faq_query->have_posts() ) : $faq_query->the_post(); ?>
<li>
<h3><span class="bullet"><?php echo $faq_count++; ?></span> <?php the_title(); ?></h3>
<div class="answer">
<?php the_content(); ?>
</div>
</li>
<?php endwhile; ?>
</ul>
<?php $faqposts = ob_get_clean();
endif; wp_reset_postdata();
$return = array(
'faqposts' => $faqposts
);
wp_send_json($return);
}
add_action( 'wp_ajax_filter_faqs', 'ajax_filter_faqs_handler' );
add_action( 'wp_ajax_nopriv_filter_faqs', 'ajax_filter_faqs_handler' );
Basically I have tabs like All, Tech, Food. And I am using ajax to filter it. The problem is that FAQ JS and CSS is not working at all on ajax request.
This works fine for me.
<script>
jQuery(document).ready(function(){
jQuery('.accordion-list > li > .answer').hide();
jQuery('body').on('click','.accordion-list > li',function(){
// jQuery('.accordion-list > li').click(function() {
if (jQuery(this).hasClass("active")) {
jQuery(this).removeClass("active").find(".answer").slideUp();
} else {
jQuery(".accordion-list > li.active .answer").slideUp();
jQuery(".accordion-list > li.active").removeClass("active");
jQuery(this).addClass("active").find(".answer").slideDown();
}
return false;
});
});
</script>

How can i show Google Adsense Ads in my Wordpress Site Homepage, in between posts Grid layout, not inside posts

How can I show "Google Ad-sense Ads" in my "WordPress" Site "Homepage", in between posts Grid layout? not inside posts. For Homepage King-composer plugin is used and want to show 'Google Ads' after specific posts only as may ads as possible. Please Help me with this. I tried many ways and used some plugins also. but nothing works.
Attaching Code file which we want to code to display Google ads.. and also attaching Homepage screenshot where I want to show ads in between the grid layout posts, not inside posts... Help me, please.
<?php
extract( shortcode_atts( array(
'ads_source' => 'by_choice',
'topads' => 'no',
'post_ids' => '',
'post_number' => '6',
'category_ids' => '',
'location_ids' => '',
'type' => '',
'orderby' => '',
'order' => '',
'style' => 'grid',
'slider' => 'no',
'visible_items' => '',
'autoplay_speed' => '',
'double_row' => '',
'items_in_row' => '4'
), $atts ) );
if( $ads_source == 'by_choice' ){
$args = array(
'post__in' => explode( ',', $post_ids ),
'orderby' => 'post__in'
);
}
else{
$args = array(
'posts_per_page' => $post_number,
'orderby' => $orderby,
'order' => $order,
);
if( $topads == 'yes' ){
$args['post__in'] = adifier_topads_ids_list();
}
if( !empty( $category_ids ) ){
$args['tax_query'] = array(
array(
'taxonomy' => 'advert-category',
'terms' => explode( ',', $category_ids )
)
);
}
if( !empty( $location_ids ) ){
$args['tax_query'] = array(
array(
'taxonomy' => 'advert-location',
'terms' => explode( ',', $location_ids )
)
);
}
}
if( !empty( $type ) ){
$args['type'] = $type;
}
$args['post_status'] = 'publish';
$adverts = new Adifier_Advert_Query( $args );
if( $adverts->have_posts() ){
if( $style == 'big_slider' ){
?>
<div class="adverts-big-slider owl-carousel">
<?php
while( $adverts->have_posts() ){
$adverts->the_post();
?>
<div class="white-block hover-shadow">
<a href="<?php the_permalink() ?>" class="advert-media">
<?php adifier_get_advert_image('adifier-single-slider') ?>
</a>
<div class="white-block-content">
<?php include( get_theme_file_path( 'includes/advert-boxes/top-meta.php' ) ) ?>
<?php include( get_theme_file_path( 'includes/advert-boxes/title.php' ) ) ?>
<?php include( get_theme_file_path( 'includes/advert-boxes/bottom-meta.php' ) ) ?>
</div>
</div>
<?php
}
?>
</div>
<?php
}
else{
$max = $double_row == 'yes' ? 2 : 1;
$counter = 0;
?>
<div class="adverts-list clearfix <?php echo $slider == 'yes' ? esc_attr( 'adverts-slider owl-carousel' ) : esc_attr( 'af-items-'.$items_in_row ) ?>" data-visibleitems="<?php echo esc_attr( $visible_items ) ?>" data-autoplay="<?php echo esc_attr( $autoplay_speed ) ?>">
<div class="af-item-wrap">
<?php
while( $adverts->have_posts() ){
$adverts->the_post();
if( $max == $counter ){
?>
</div><div class="af-item-wrap">
<?php
$counter = 0;
}
$counter++;
if( $style == 'list' ){
$limit = 80;
}
include( get_theme_file_path( 'includes/advert-boxes/'.$style.'.php' ) );
}
?>
</div>
</div>
<?php
}
?>
<?php
}
wp_reset_postdata();
?>
My Home Page image screenshot where I want to show Google ads in between Grid Layout :

How to Add Ajax Pagination On Ajax Post filter Result

I am developing a website with taxonomy filter. I have created taxonomy widget like this
Tax A
Tax B
Tax C
Tax D
And place one apply filter below that when i clicking apply filter it will filter post by Ajax request and Append Post on HTML. Now I want to show Ajax load More Button on Filter Ajax result i have added some code for load more but its fetching post from all taxonomy. I want to work the load more like this if i filter Tax A and i want to show post in Tax A taxonomy on load More.
Following are my code:
On Function.php
function misha_my_load_more_button_scripts() {
global $wp_query;
wp_register_script( 'misha_filter_scripts', get_stylesheet_directory_uri().'/custom.js', array('jquery'), '1.0.0', true );
wp_enqueue_script( 'misha_filter_scripts' );
// now the most interesting part
// we have to pass parameters to myloadmore.js script but we can get the parameters values only in PHP
// you can define variables directly in your HTML but I decided that the most proper way is wp_localize_script()
wp_localize_script( 'misha_filter_scripts', 'misha_loadmore_button_params', array(
'ajaxurl' => site_url() . '/wp-admin/admin-ajax.php', // WordPress AJAX
'posts' => json_encode( $wp_query->query_vars ), // everything about your loop is here
'current_page' => $wp_query->query_vars['paged'] ? $wp_query->query_vars['paged'] : 1,
'max_page' => $wp_query->max_num_pages
) );
}
add_action( 'wp_enqueue_scripts', 'misha_my_load_more_button_scripts', 1 );
//functon for ajax blog filter
add_action('wp_ajax_myfilter', 'wph_filter_function'); // wp_ajax_{ACTION HERE}
add_action('wp_ajax_nopriv_myfilter', 'wph_filter_function');
function wph_filter_function(){
// $CurrentPage = get_query_var('paged');
//$paged = $_POST['paged'];
//wp_reset_postdata();
if( isset( $_POST['categoryfilter'] ) ){
$category_post = $_POST['categoryfilter'];
}
if( isset( $_POST['categoryfilter_prod'] ) ){
$category_product = $_POST['categoryfilter_prod'];
}
if( isset( $_POST['categoryfilter_resource'] ) ){
$category_resource = $_POST['categoryfilter_resource'];
}
//var_dump($category_post);
//var_dump($category_product);
//var_dump($category_resource);
$tax_query = array('relation' => 'AND');
if (isset($_POST['categoryfilter']))
{
$tax_query[] = array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $category_post
);
}
if (isset($_POST['categoryfilter_prod']))
{
$tax_query[] = array(
'taxonomy' => 'cat_product',
'field' => 'id',
'terms' => $category_product
);
}
if (isset($_POST['categoryfilter_resource']))
{
$tax_query[] = array(
'taxonomy' => 'resource',
'field' => 'id',
'terms' => $category_resource
);
}
$query = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' =>30,
'orderby' => 'date',
'order' => 'DESC',
'paged' => $CurrentPage,
'tax_query' => $tax_query,
)
);
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
?>
<?php if( get_field('show_login_only') ): ?>
<div class="res-entry">
<div class="row">
<div class="col-md-4">
<?php
if ( has_post_thumbnail()) the_post_thumbnail('resource-blog');
?>
</div>
<div class="col-md-8 blog-details">
<a class="related-title" href="<?php the_permalink(); ?>" title="<?php echo esc_attr( the_title_attribute( 'echo=0' ) ); ?>"><?php the_title(); ?></a>
<br>
<div class="posted-date">
<?php palliance_posted_on_noslash(); ?>
</div>
<div class="post-less">
<?php echo excerpt(20); ?>
</div>
</div>
</div>
</div>
<?php endif; ?>
<?php
endwhile;
wp_reset_postdata();
if ( $query->max_num_pages > 1 ) :
echo '<div id="misha_loadmore">More posts</div>'; // you can use <a> as well
endif;
else :
echo 'No posts found';
endif;
die();
}
add_action('wp_ajax_loadmorebutton', 'misha_loadmore_button_ajax_handler');
add_action('wp_ajax_nopriv_loadmorebutton', 'misha_loadmore_button_ajax_handler');
function misha_loadmore_button_ajax_handler(){
$args = unserialize( stripslashes( $_POST['query']) );
$args['paged'] = $_POST['page'] + 1;
$args['post_status'] = 'publish';
$query = new WP_Query( $args );
global $wp_query;
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
?>
<div class="res-entry">
<div class="row">
<div class="col-md-4">
<?php
if ( has_post_thumbnail()) the_post_thumbnail('resource-blog');
?>
</div>
<div class="col-md-8 blog-details">
<a class="related-title" href="<?php the_permalink(); ?>" title="<?php echo esc_attr( the_title_attribute( 'echo=0' ) ); ?>"><?php the_title(); ?></a>
<br>
<div class="posted-date">
<?php palliance_posted_on_noslash(); ?>
</div>
<div class="post-less">
<?php echo excerpt(20); ?>
</div>
</div>
</div>
</div>
<?php
endwhile;
else :
get_template_part( 'template-parts/content', 'none' );
endif;
die;
}
Jquery Code is following
jQuery(function($){
$('#filter').on('change', 'input[type=checkbox]', function() {
setTimeout(function(){
// $(".filter-btn").click();
},1);
});
$('#clear-all-filter-1').click(function() {
$(".filter-form input[type=checkbox]").attr("checked", false);
setTimeout(function(){
$(".filter-btn").click();
},1);
});
$('#clear-all-filter-2').click(function() {
$(".filter-form input[type=checkbox]").attr("checked", false);
setTimeout(function(){
$(".filter-btn").click();
},1);
});
$('#filter').submit(function(){
var filter = $('#filter');
var response = $('#response');
$.ajax({
//url:filter.attr('action'),
url : misha_loadmore_button_params.ajaxurl,
data : $('#filter').serialize(), // form data
// dataType : 'json', // this data type allows us to receive objects from the server
type : 'POST',
beforeSend:function(xhr){
filter.find('.filter-btn').text('Processing...'); // changing the button label
//response.find('.res-entry').css("background-color", "yellow"); // changing the button label
},
success:function(data){
misha_loadmore_button_params.current_page = 1;
// set the new query parameters
misha_loadmore_button_params.posts = data.posts;
// set the new max page parameter
misha_loadmore_button_params.max_page = data.max_page;
filter.find('.filter-btn').text('Apply filter'); // changing the button label back
//$('#response').html(data); // insert data
$("#response").html('');
$("#response").append(data);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
return false;
});
});
jQuery(document).ready( function($) {
/*
* Load More
*/
$('#misha_loadmore').click(function(){
$.ajax({
url : misha_loadmore_button_params.ajaxurl, // AJAX handler
data : {
'action': 'loadmorebutton', // the parameter for admin-ajax.php
'query': misha_loadmore_button_params.posts, // loop parameters passed by wp_localize_script()
'page' : misha_loadmore_button_params.current_page // current page
},
type : 'POST',
beforeSend : function ( xhr ) {
$('#misha_loadmore').text('Loading...'); // some type of preloader
},
success : function( data ){
if( data ) {
$('#misha_loadmore').text( 'More posts' );
$('#response').append(data); // insert new posts
misha_loadmore_button_params.current_page++;
if ( misha_loadmore_button_params.current_page == misha_loadmore_button_params.max_page )
$('#misha_loadmore').hide(); // if last page, HIDE the button
} else {
$('#misha_loadmore').hide(); // if no data, HIDE the button as well
}
}
});
return false;
});
});
I think you need to use json_encode to get the current $query_var for the selected filters!
Added ob_start(); and ob_get_contents(); to pass posts to variable
Change you filter function with this and tell me if it work.
I hope it help!
//functon for ajax blog filter
add_action('wp_ajax_myfilter', 'wph_filter_function'); // wp_ajax_{ACTION HERE}
add_action('wp_ajax_nopriv_myfilter', 'wph_filter_function');
function wph_filter_function(){
// $CurrentPage = get_query_var('paged');
//$paged = $_POST['paged'];
//wp_reset_postdata();
if( isset( $_POST['categoryfilter'] ) ){
$category_post = $_POST['categoryfilter'];
}
if( isset( $_POST['categoryfilter_prod'] ) ){
$category_product = $_POST['categoryfilter_prod'];
}
if( isset( $_POST['categoryfilter_resource'] ) ){
$category_resource = $_POST['categoryfilter_resource'];
}
//var_dump($category_post);
//var_dump($category_product);
//var_dump($category_resource);
$tax_query = array('relation' => 'AND');
if (isset($_POST['categoryfilter']))
{
$tax_query[] = array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $category_post
);
}
if (isset($_POST['categoryfilter_prod']))
{
$tax_query[] = array(
'taxonomy' => 'cat_product',
'field' => 'id',
'terms' => $category_product
);
}
if (isset($_POST['categoryfilter_resource']))
{
$tax_query[] = array(
'taxonomy' => 'resource',
'field' => 'id',
'terms' => $category_resource
);
}
$query = new WP_Query( array(
'post_type' => 'post',
'posts_per_page' =>30,
'orderby' => 'date',
'order' => 'DESC',
'paged' => $CurrentPage,
'tax_query' => $tax_query,
)
);
if( $query->have_posts() ) :
ob_start();
while( $query->have_posts() ): $query->the_post();
?>
<?php if( get_field('show_login_only') ): ?>
<div class="res-entry">
<div class="row">
<div class="col-md-4">
<?php
if ( has_post_thumbnail()) the_post_thumbnail('resource-blog');
?>
</div>
<div class="col-md-8 blog-details">
<a class="related-title" href="<?php the_permalink(); ?>" title="<?php echo esc_attr( the_title_attribute( 'echo=0' ) ); ?>"><?php the_title(); ?></a>
<br>
<div class="posted-date">
<?php palliance_posted_on_noslash(); ?>
</div>
<div class="post-less">
<?php echo excerpt(20); ?>
</div>
</div>
</div>
</div>
<?php endif; ?>
<?php
endwhile;
wp_reset_postdata();
if ( $query->max_num_pages > 1 ) :
echo '<div id="misha_loadmore">More posts</div>'; // you can use <a> as well
endif;
$content = ob_get_contents(); // we pass the posts to variable
ob_end_clean(); // clear the buffer
else :
ob_start(); // start the buffer to capture the output of the template
get_template_part( 'template-parts/content', 'none' );
$content = ob_get_contents(); // pass the output to variable
ob_end_clean();
endif;
echo json_encode( array(
'posts' => json_encode( $wp_query->query_vars ),
'max_page' => $wp_query->max_num_pages,
'found_posts' => $wp_query->found_posts,
'content' => $content
));
die();
}

Categories

Resources