Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Wordpress - filter post by tags using AJAX.
(function($) {
$doc = $(document);
$doc.ready( function() {
var container = $('#main');
var pagePosts = container.find('article');
var postNav = $('nav.navigation');
var catName = "";
var name = "";
var page = "1";
var clickTag = "";
var n = "";
$("a[rel='tag']").addClass("ajax_tag");
function get_posts($params){
$.ajax({
url: mdu.ajax_url,
data: {
action: 'my_get_posts',
nonce: mdu.nonce,
params: $params,
},
type: 'POST',
dataType:'json',
success: function(data,XMLHttpRequest){
pagePosts.remove();
postNav.remove();
container.html(data.content);
container.append(data.navigation);
postNav = $('nav.navigation');
$("a[rel='tag']").addClass("ajax_tag");
},
});
}
function getCatName(name){
var pattern = /[^ *-]\w+$/g;
n = $("h1").html();
catName = pattern.exec(n);
}
container.on('click', "a[rel='tag'], .pagination a", function(event) {
$this = $(this);
event.preventDefault();
if ($this.hasClass('ajax_tag')) {
clickTag = $this.text();
getCatName(name);
page = "1";
}
else {
page = parseInt($this.attr('href').replace(/\D/g,''));
}
$params = {
'tag' : clickTag,
'cat' : catName,
'pagenum': page,
};
get_posts($params);
});
});
})(jQuery);
<?php
/**
*
* Functions and definitons
* This is a child theme of Twentysixteen theme
* V1.0 - AJAX Filter posts
* Largely inspired by Vlado Bosnjak work that you can find here:
* https://www.bobz.co/filter-wordpress-posts-by-custom-taxonomy-term-with-ajax-and-pagination/
*
*
*/
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
$parent_style = 'twentysixteen-style';
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
}
function my_get_posts(){
if( !isset( $_POST['nonce'] ) || !wp_verify_nonce( $_POST['nonce'], 'mdu' ) )
die('MDU Permission denied' );
$ajax_tag = ($_POST['params']['tag']);
$ajax_cat = ($_POST['params']['cat']);
$page = ($_POST['params']['pagenum']);
/**
* Here we setup our custom WordPress query to retreive the post we want.
*/
$args = [
'paged' => $page,
'post_type' => 'post',
'post_status' => 'publish',
'tag' => $ajax_tag,
'category_name' => $ajax_cat,
];
$my_query = new WP_Query( $args );
if (ob_get_level()) ob_end_clean();
ob_start();
if ($my_query->have_posts()) :
while ($my_query->have_posts()) : $my_query->the_post();
$post_content = get_template_part( 'template-parts/content', get_post_format() );
endwhile;
ob_start();
$nav_content = vb_ajax_pager($my_query,$page);
endif;
$nav_content = ob_get_clean();
$post_content = ob_get_clean();
$response = ['content' => $post_content , 'navigation' => $nav_content,];
die(json_encode($response));
}
add_action('wp_ajax_my_get_posts', 'my_get_posts');
add_action('wp_ajax_nopriv_my_get_posts', 'my_get_posts');
/**
* Pagination for the tag view.
* Here I'm buildn't the pagination element for my custom query
*/
function vb_ajax_pager ( $query = NULL, $paged = 1 ) {
$ajax_paginate[] = 1;
if (!$query)
return;
$ajax_paginate = paginate_links([
'base' => '%_%',
'type' => 'array',
'total' => $query->max_num_pages,
'format' => '#page=%#%',
'current' => max( 1, $paged ),
'prev_text' => '&lt;',
'next_text' => '&gt;'
]);
/**
* Here below i'm building the navigation bar,
* I'm rebuild it to be exactly the same as the original one
*/
if ($query->max_num_pages > 1) : ?>
<nav class="navigation pagination" role="navigation">
<h2 class="screen-reader-text">Posts navigation</h2>
<div class="nav-links">
<?php foreach ( $ajax_paginate as $ajax_page ): ?>
<span class="page-numbers"><?php echo $ajax_page; ?></span>
<?php endforeach; ?>
</div>
</nav>
<?php endif;
}
/**
* And finaly i'm doing the enqueue and localizing the Javascript.
*/
function assets() {
wp_register_script('ajax_filter', get_stylesheet_directory_uri() . '/js/ajax-filter-posts.js', ['jquery'], "1.0", true);
wp_enqueue_script('ajax_filter');
wp_localize_script( 'ajax_filter', 'mdu', array(
'nonce' => wp_create_nonce( 'mdu' ),
'ajax_url' => admin_url( 'admin-ajax.php' )
));
}
add_action('wp_enqueue_scripts', 'assets', 99);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment