On my blog page, I have created a dropdown of all the categories with their url as the value. I’m still learning how to use ajax but I am trying to load posts based on the category selected. After reading this discussion I have gotten my admin ajax to load properly, but when you select a dropdown item it still pulls all posts instead of just the category. I can tell because my “console.log(got);” shows me it grabbed a page with the body class of “blog app-data index-data home-data”. I’m not sure if I have added my helper incorrectly or I am setting up my ajax url incorrectly?
home.php
<h2 class="title-template"><?php echo (is_home() ? __('Blog') : get_the_archive_title()); ?></h2>
<?php
$cat_terms = get_terms(array('taxonomy' => 'category'));
?>
<form action="" method="post" id="blog-filter">
Filter By <select name="blog_sort" id="blog-cat-menu">
<option value="<?php echo get_permalink(get_option('page_for_posts')); ?>" selected><?php _e('All Categories'); ?></option>
@foreach($cat_terms as $t)
<option value="<?php echo get_term_link($t); ?>"><?php echo $t->name; ?></option>
@endforeach
</select>
</form>
<div class="blog-wrap">
<ul class="my-blogs">
<?php while ( have_posts() ) : the_post(); ?>
@include('partials.content')
<?php endwhile; ?>
</ul>
</div>
setup.php
add_action('wp_enqueue_scripts', function () {
wp_enqueue_style('sage/main.css', asset_path('styles/main.css'), false, null);
wp_enqueue_script('sage/main.js', asset_path('scripts/main.js'), ['jquery'], null, true);
$ajax_params = array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'ajax_nonce' => wp_create_nonce( 'my_nonce' ),
);
wp_localize_script( 'sage/main.js', 'ajax_object', $ajax_params);
}, 100);
common.js
$(document).on('change', '#blog-cat-menu', function() {
var theForm = $(this);
$.ajax({
url: ajax_object.ajax_url,
data: theForm.serialize() + '&action=filter_posts',
type: 'POST',
dataType: 'json',
beforeSend: function() {
$('body').addClass('ajax-sort');
},
success: function(data) {
$.get(data.url, function(got) {
console.log(got);
$('.blog-wrap').replaceWith($(got).find('.blog-wrap'));
$('.title-template').replaceWith($(got).find('.title-template'));
})
.done(function() {
$('body').removeClass('ajax-sort');
});
},
});
return false;
});
console.log(ajax_object);
helpers.php
function ajax_filter_categories() {
echo json_encode(array('url' => $_POST['blog_sort']));
die();
}
add_action('wp_ajax_filter_posts', 'ajax_filter_categories');
add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_categories');