'Specific page with ajax filter
I made a function that filters wordpress categories
functions.php
function load_scripts() {
wp_enqueue_script('ajax', get_template_directory_uri() . '/vendor/jquery/main.js', array('jquery'), NULL, true);
wp_localize_script('ajax' , 'wp_ajax',
array('ajax_url' => admin_url('admin-ajax.php'))
);
}
add_action( 'wp_enqueue_scripts', 'load_scripts');
add_action( 'wp_ajax_nopriv_filter', 'filter_ajax' );
add_action( 'wp_ajax_filter', 'filter_ajax' );
function filter_ajax() {
$category = $_POST['category'];
if(isset($_POST['pageslug']) && $_POST['pageslug'] === 'faq'){
$cat__in = 10;
print_r( $_POST );
echo "FAQ";
} else{
$cat__in = 4;
print_r( $_POST );
echo "Products";
}
$args = array(
'post_type' => 'post',
'posts_per_page' => 50,
'category__in' => $cat__in,
);
if(isset($category)) {
$args['category__in'] = array($category);
}
$query = new WP_Query($args);
if($query->have_posts()) :
while($query->have_posts()) : $query->the_post();
the_title('<h2>', '</h2>');
the_content('<p>', '</p>');
endwhile;
endif;
wp_reset_postdata();
die();
}
I want the displayed categories to be different on the "FAQ" and "PRODUCTS" pages, so I used
if(isset($_POST['pageslug']) && $_POST['pageslug'] === 'faq'){
$cat__in = 10;
} else{
$cat__in = 4;
}
but since I'm using ajax, the function doesn't recognize pages.
main.js
(function($){
$(document).ready(function(){
$(document).on('click', '.js-filter-item > a', function(e){
e.preventDefault();
var category = $(this).data('category');
$.ajax({
url:wp_ajax.ajax_url,
data: {
action: 'filter',
category: category,
id: location.pathname.replace(/\//g,'')
},
type: 'post',
success: function(result) {
$('.js-filter').html(result);
},
error: function(result) {
console.warn(result);
}
});
});
});
})(jQuery);
What am I doing wrong? I tried that way too, but it doesn't work either functions.php
if (is_page('faq') ) {
$cat__in = 10;
} else {
$cat__in = 6;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
