Skip to content

Instantly share code, notes, and snippets.

@aaronsummers
Last active November 30, 2022 06:21
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save aaronsummers/b00caa8ee3c1ce18e6c8da0d2d10dd44 to your computer and use it in GitHub Desktop.
Save aaronsummers/b00caa8ee3c1ce18e6c8da0d2d10dd44 to your computer and use it in GitHub Desktop.
Ajax filter for WordPress posts

Ajax post filter for WordPress

Part 1

  • First create a post grid ( 3 Column )
  • Add our CSS
    • Post grid
    • Filter
<?php
$object = get_queried_object();
$has_category = (is_category()) ? $object->term_id : '';
$args = array(
'posts_per_page' => 6,
'ignore_sticky_posts' => 1,
);
if ($object != null) :
// If we're on a category page update the args
$args = array(
'posts_per_page' => 6,
'ignore_sticky_posts' => 1,
'cat' => $has_category
);
endif;
$loop = new WP_Query($args);
$total_posts = $loop->found_posts; // Get the total posts for this query
if ($loop->have_posts()) : ?>
<div class="aa-recent-posts-wrapper">
<div class="aa-three-column-flex recent-posts">
<?php while ($loop->have_posts()) : $loop->the_post(); ?>
<?php
$terms = get_the_terms(get_the_ID(), 'category');
$term_as_class = ' ' .$terms[0]->slug. ' ';
$permalink = get_the_permalink();
?>
<a <?php post_class('aa-article' . $term_as_class); ?> href="<?php echo $permalink; ?>">
<div class="aa-post-image" style="background-image: url(<?php echo the_post_thumbnail_url('medium'); ?>)"></div><!-- /.post-image -->
<div class="aa-post-excerpt">
<h2 class="h5"><?php the_title(); ?></h2>
<span class="date-label">
<span class="date-posted-on"><?php echo $date_posted_on; ?></span>
<?php the_time('d/m/Y'); ?>
</span><!-- /.date_label -->
<div class="aa-read-more">Read more</div><!-- /.aa-read-more -->
</div><!-- /.post-excerpt -->
</a><!-- /.article -->
<?php endwhile; wp_reset_postdata(); ?>
</div> <!-- /.aa-three-column-flex recent-posts -->
<?php
/**
* Build our rest url for the hidden field,
* This is used later for our load more.
*/
$custom_rest_url = "/blog/wp-json/wp/v2/posts?per_page=6";
if (is_category()) :
$custom_rest_url .= '&categories=' . $has_category;
endif;
?>
<input class="aa-current-tag_id" type="hidden" value="">
<input class="aa-request-url" type="hidden" value="<?php echo $custom_rest_url; // Used for the load more ?>">
<input class="aa-total-pages" type="hidden" value="<?php echo $total_posts; // initially added from post count, then updated with ajax. ?>">
<input class="aa-current-category" type="hidden" value="<?php echo $has_category; // Store the category and grab this in our request ?>">
<div class="aa-total-posts">
<span class="current-post-count">6</span>
<span class="x-out-of-n"> out of </span>
<span class="total-posts"><?php echo $total_posts; ?></span>
<span class="articles"> articles</span>
</div><!-- /.total-posts -->
<div class="aa-load-more-wrapper">
<a data-page="2" <?php // data attr gives us a starting page number, then becomes updated with a simple click ?>
class="button aa-loadmore"
href="<?php echo $custom_rest_url; ?>"
tabindex="0">
<i class="icon icon-arrow-down"><?php // Icon required! ?></i>
</a>
<div class="aa-load-more-text">Load more</div>
</div><!-- /.load-more-wrapper -->
</div><!-- /.recent-posts-wrapper -->
<?php endif; // if (have_posts()) :
.h5 {
font-family: 'Arial';
font-weight: 700;
font-size: 1rem;
line-height: 1;
}
@media (min-width: 720px) {
.h5 {
font-size: 20px;
line-height: 20px;
}
}
.recent-posts {
min-height: 300px
}
.load-more-wrapper .load-more-text {
font-size: .8rem;
margin-top: 1em;
}
.load-more-wrapper {
margin-bottom: 2rem;
text-align: center;
}
.aa-recent-posts-wrapper .aa-loadmore {
background-color: rgba(69, 139, 0, .85);
-webkit-transform: rotate(180deg);
transform: rotate(180deg);
width: 50px;
display: inline-block;
min-width: 50px;
height: 50px;
line-height: 50px;
text-align: center;
padding: 0 !important;
-webkit-transition: margin ease-in-out .18s;
transition: margin ease-in-out .18s;
will-change: margin;
-webkit-box-shadow: 0px -3px 4px rgba(0,0,0,.2);
box-shadow: 0px -3px 4px rgba(0,0,0,.2);
}
.aa-recent-posts-wrapper {
padding-bottom: 54px;
}
.aa-recent-posts-wrapper .aa-loadmore .icon {
font-size: 1.813rem;
line-height: 50px;
margin: 0;
}
.aa-recent-posts-wrapper .aa-loadmore:hover {
margin: .5rem 0 -.5rem;
}
.aa-recent-posts-wrapper .aa-loadmore.loading .icon {
display: none;
}
.aa-recent-posts-wrapper .aa-loadmore.loading {
background: url(ajax-loader.gif) no-repeat 50% 50% / contain;
-webkit-box-shadow: none;
box-shadow: none;
}
.aa-recent-posts-wrapper.loading {
background: url(ajax-loader.gif) no-repeat 50% 15%;
}
.aa-three-column-flex {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
-webkit-box-orient: horizontal;
-webkit-box-direction: normal;
-ms-flex-flow: row wrap;
flex-flow: row wrap;
}
.aa-three-column-flex .aa-article {
width: 100%;
margin: 0 0 1rem;
overflow: hidden;
border-style: solid;
border-width: 2px;
color: black;
position: relative;
}
.aa-article {
border-color: #000;
}
.aa-three-column-flex .aa-article:hover {
text-decoration: none;
}
@media (min-width: 500px) and (max-width: 768px) {
.aa-three-column-flex .aa-article {
width: calc(50% - 2rem);
}
.aa-three-column-flex .aa-article {
margin: 0 0 1rem 1rem;
}
}
@media (min-width: 768px) {
.aa-three-column-flex .aa-article {
width: calc(33% - .8rem);
margin: 0 .3rem .6rem;
}
}
.aa-article .aa-post-excerpt {
padding: .8rem .8rem 3.5rem;
z-index: 2;
background: white;
}
.aa-article .aa-post-image {
background-size: cover;
background-position: 50% 50%;
padding-bottom: 100%;
-webkit-transform: scale(1);
transform: scale(1);
-webkit-transition: -webkit-transform .3s ease;
transition: -webkit-transform .3s ease;
transition: transform .3s ease;
transition: transform .3s ease, -webkit-transform .3s ease;
will-change: transform;
}
@media (max-width: 600px) {
.aa-article .aa-post-image {
padding-bottom: 70%;
}
}
.aa-article:hover .aa-post-image {
-webkit-transform: scale(1.1);
transform: scale(1.1);
}
.aa-article .aa-read-more,
.aa-article .aa-read-more:after {
color: black;
font-weight: 800;
font-family: Officina Sans;
}
.aa-article .aa-read-more {
position: absolute;
bottom: .8rem;
right: .8rem;
font-size: 1rem;
}
.aa-article .aa-read-more::after {
content: " >";
font-size: 1.2rem;
bottom: -2px;
position: relative;
}
.aa-article {
position: relative;
padding-bottom: 1.4rem;
cursor: pointer;
}
.aa-article .date_label {
display: block;
margin-top: .2rem;
}
.aa-recent-posts-wrapper .aa-total-posts,
.aa-recent-posts-wrapper .aa-total-posts span {
text-align: center;
color: #9AA2B0;
font-family: Arial;
font-weight: 700;
}
.aa-recent-posts-wrapper .aa-total-posts {
margin: 1rem 0;
}
.aa-tag-wrapper {
margin-bottom: 1rem;
}
@media (min-width: 800px) {
.aa-tag-wrapper {
display: flex;
}
}
.aa-tag-wrapper .aa-sortby {
font-family: Arial;
font-size: 14px;
font-weight: 700;
position: relative;
margin-top: .6rem;
cursor: pointer
}
@media (min-width: 800px) {
.aa-tag-wrapper .aa-sortby-wrapper,
.aa-tag-wrapper .aa-sortby {
max-width: 160px;
min-width: 130px;
width: 100%;
}
}
@media (max-width: 800px) {
.aa-tag-wrapper .aa-sortby-wrapper {
display: flex;
margin-bottom: 1rem;
}
.aa-tag-wrapper .aa-sortby {
border: solid 2px;
width: calc(50% - .4rem);
text-align: center;
height: 50px;
display: flex;
justify-content: center;
align-items: center;
}
.aa-tag-wrapper .aa-sortby + .aa-sortby {
margin-left: auto;
}
.aa-sortby::before {
left: 1rem;
}
.aa-sortby::after {
left: 1rem;
}
}
.aa-sortby span {
position: relative;
display: inline-block;
width: 16px;
height: 16px;
margin-right: .8rem;
}
.aa-sortby span::before,
.aa-sortby span::after {
content: "";
display: block;
border-radius: 50%;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
.aa-sortby span::before {
width: 16px;
height: 16px;
left: 0;
border: solid 2px;
}
.aa-sortby.active span::after {
background: #458B00;
width: 12px;
height: 12px;
left: 4px;
}

Part 2

  • Add a meta couter field to collect popular posts
  • Register the meta field for the rest api
  • Register the script for our ajax filter
<?php
/**
* Add a couter field to collect popular posts
*/
function aa_set_post_views($postID) {
$count_key = 'aa_post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
$count = 0;
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
}else{
$count++;
update_post_meta($postID, $count_key, $count);
}
}
//To keep the count accurate, lets get rid of prefetching
remove_action( 'wp_head', 'adjacent_posts_rel_link_wp_head', 10, 0);
function aa_track_post_views ($post_id) {
if ( !is_single() ) return;
if ( empty ( $post_id) ) {
global $post;
$post_id = $post->ID;
}
aa_set_post_views($post_id);
}
add_action( 'wp_head', 'aa_track_post_views');
function aa_get_post_views($postID){
$count_key = 'aa_post_views_count';
$count = get_post_meta($postID, $count_key, true);
if($count==''){
delete_post_meta($postID, $count_key);
add_post_meta($postID, $count_key, '0');
return "0 View";
}
return $count.' Views';
}
add_action( 'transition_post_status', 'aa_new_post_creation', 10, 3);
function aa_new_post_creation($new_status, $old_status, $post) {
$count_key = 'aa_post_views_count';
if($new_status == 'publish' && $old_status != 'publish' && in_array($post->post_type, array('post', 'page'))) {
$count = get_post_meta($post->ID, $count_key, true);
if ($count == '') {
add_post_meta($post->ID, $count_key, '0');
}
}
}
/**
* Register the meta field for the rest api
*/
add_action( 'rest_api_init', 'aa_register_postviews_meta_fields');
function aa_register_postviews_meta_fields(){
register_meta( 'post', 'aa_post_views_count', array(
'type' => 'integer',
'description' => 'Post views',
'single' => true,
'show_in_rest' => true
));
}
//https://github.com/WP-API/WP-API/issues/2308#issuecomment-262886432
add_filter('rest_endpoints', function ($routes) {
// I'm modifying multiple types here, you won't need the loop if you're just doing posts
foreach (['post'] as $type) {
if (!($route =& $routes['/wp/v2/' . $type])) {
continue;
}
// Allow ordering by my meta value
$route[0]['args']['orderby']['enum'][] = 'meta_value_num';
// Allow only the meta keys that I want
$route[0]['args']['meta_key'] = array(
'description' => 'The meta key to query.',
'type' => 'string',
'enum' => ['aa_post_views_count'],
'validate_callback' => 'rest_validate_request_arg',
);
}
return $routes;
});
//https://github.com/WP-API/WP-API/issues/2308#issuecomment-265875108
add_filter('rest_post_query', function ($args, $request) {
if ($key = $request->get_param('meta_key')) {
$args['meta_key'] = $key;
}
return $args;
}, 10, 2);
// This enables the orderby=meta_value_num for Posts
add_filter( 'rest_post_collection_params', 'aa_filter_add_rest_orderby_params', 10, 1 );
/**
* Add meta_value_num to the list of permitted orderby values
*/
function aa_filter_add_rest_orderby_params( $params ) {
$params['orderby']['enum'][] = 'meta_value_num';
return $params;
}
/**
* Register the script for our ajax filter
*/
function aa_styles_scripts(){
$error_message = 'Sorry something went wrong!';
$warning_icon = '/wp-content/themes/theme-name/assets/images/warning.png'; // Icon, shown with the error message
$custom_rest_url = "/wp-json/wp/v2/posts"; // Raltive path for the REST API
$ajax_file_url = '/assets/js/aa-ajax-load-posts.js';
$ajax_revision = '10.12.2019.1424';
wp_register_script( 'ajax-load-posts', get_template_directory_uri() . $ajax_file_url , array('jquery'), $ajax_revision,true);
// Localise some wordpress things to be called in the ajax-posts.js
wp_localize_script(
'ajax-load-posts',
'aa_opt',
array(
'jsonUrl' => $custom_rest_url,
'warningImageUrl' => $warning_icon,
'errorMessage' => $error_message
)
);
wp_enqueue_script('ajax-load-posts');
}
add_action( 'wp_enqueue_scripts', 'aa_styles_scripts' );
/**
* Inmclude the featured image in the REST API
*/
add_action('rest_api_init', 'aa_register_rest_images' );
function aa_register_rest_images(){
register_rest_field( array('post'),
'featured_image_url', // Rest API - object.featured_image_url
array(
'get_callback' => 'aa_get_rest_featured_image',
'update_callback' => null,
'schema' => null,
)
);
}
function aa_get_rest_featured_image( $object, $field_name, $request ) {
if( $object['featured_media'] ){
$img = wp_get_attachment_image_src( $object['featured_media'], 'medium' );
return $img[0];
}
return false;
}

Part 3

  • Tag and Sort Filter
<?php
// Get tags IN USE by category id
function get_tags_in_use($category_ID, $type = 'name'){
// Set up the query for our posts
$my_posts = new WP_Query(array(
'cat' => $category_ID, // Your category id
'posts_per_page' => -1 // All posts from that category
));
// Initialize our tag arrays
$tags_by_id = array();
// If there are posts in this category, loop through them
if ($my_posts->have_posts()): while ($my_posts->have_posts()): $my_posts->the_post();
// Get all tags of current post
$post_tags = wp_get_post_tags($my_posts->post->ID);
// Loop through each tag
foreach ($post_tags as $tag):
// Set up our tags by id, name, and/or slug
$tag_id = $tag->term_id;
// Push each tag into our main array if not already in it
if (!in_array($tag_id, $tags_by_id))
array_push($tags_by_id, $tag_id);
endforeach; // foreach ($post_tags as $tag):
endwhile; endif;
// Return value specified
if ($type == 'id')
return $tags_by_id;
}
// Output tag cloud based on category id
function tag_cloud_by_category($category_ID) {
// Create the default text content
$trending_tags = 'Trending Tags';
$explore_all_tags = 'Explore all tags';
$explore_all_tags_opened = 'Close all tags';
// Get our tag array
$tags = get_tags_in_use($category_ID, 'id');
// Start our output variable
echo '<div class="aa-post-filter" data-per-page="6">
<h5>' . $trending_tags . '</h5>';
// Setup our $term array
$term = array();
// Cycle through each tag and set it up
foreach ($tags as $tag):
// Save our terms into an array()
$term[] = get_term_by('id', $tag, 'post_tag');
endforeach; // foreach ($tags as $tag):
// Sort them by total posts
$count = array_column($term, 'count');
array_multisort($count, SORT_DESC, $term); // $term is now or sorted array
// Count the terms and seperate the first 6
$count_terms = count($count);
if ( $count_terms > 0 ) :
$total = ( $count_terms >= 6 ) ? 5 : $count_terms - 1; //let's make sure there are enough terms
echo '<ul class="menu">';
for ($i=0; $i<=$total; $i++) :
$tag = $term[$i];
$tag_name = $tag->name;
$term_data = array();
$term_data[] = 'data-filter="'.$tag->slug.'"';
$term_data[] = 'data-filter-id="'.$tag->term_id.'"';
// Get tag link
$tag_link = get_tag_link($tag);
$tag_name = (strlen($tag_name)>24) ? mb_substr($tag_name, 0, 24, 'utf8') ."..." : $tag_name;
echo '<li>';
echo '<a href="'.$tag_link.'" '.implode(' ', $term_data).' class="aajax-filter"><span>'.$tag_name.'</span></a>';
echo ' </li>';
endfor; // for ($i=0; $i<=$total; $i++) :
echo '</ul> <!-- /.menu -->';
if ( $count_terms > 6 ) :
echo '<div class="aa-has-extra-content">
<div class="aa-more-content">
<ul class="menu">';
$final_terms = array_slice($term, 6, 12); // offset the first 6 posts get another 12
foreach ( $final_terms as $tag ) :
// Get tag name
$tag_name = $tag->name;
$term_data = array();
$term_data[] = 'data-filter="'.$tag->slug.'"';
$term_data[] = 'data-filter-id="'.$tag->term_id.'"';
// Get tag link
$tag_link = get_tag_link($tag);
$tag_name = (strlen($tag_name)>24) ? mb_substr($tag_name, 0, 24, 'utf8') ."..." : $tag_name;
echo '<li>';
echo '<a href="'.$tag_link.'" '.implode(' ', $term_data).' class="aajax-filter"><span>'.$tag_name.'</span></a>';
echo ' </li>';
endforeach; // foreach ( $final_terms as $tag ) :
echo '</ul> <!-- /.menu -->
</div> <!-- /.aa-more-content -->
<span class="aa-show-more"><span class="aa-symbol">+</span> <span class="aa-closed">' . $explore_all_tags . '</span><span class="aa-opened" style="display: none;">' . $explore_all_tags_opened . '</span></span>
</div> <!-- /.aa-has-extra-content -->';
endif;
endif; // if ( $count_terms > 0 ) :
echo '</div> <!-- /.aa-post-filter -->';
}
?>
<div class="col-12 m-top-large">
<div class="heading heading--dc m-bottom-medium">
<h2 class="h2">
<span class="heading-title">All Articles</span>
</h2>
</div> <!-- /.heading heading--dc m-bottom-medium -->
<div class="c-container aa-tag-wrapper">
<div class="aa-sort-by-wrapper">
<h5>Sort by</h5>
<div class="aa-sortby-wrapper">
<div class="aa-sortby active" data-param="&order=desc"><span class="radio-button"></span> Most Recent</div>
<div class="aa-sortby" data-param="&meta_key=wpb_post_views_count&orderby=meta_value_num&order=desc"><span class="radio-button"></span> Most Popular</div>
</div>
</div><!-- /.sort-by -->
<?php
$cat_id = get_queried_object_id();
tag_cloud_by_category($cat_id); // $cat_id is the desired category id ?>
</div> <!-- /.c-container h-margin-bottom-40 -->
</div> <!-- /.col-12 m-top-large -->

Part 4

  • Ajax
(function($){
"use strict";
// Set the total pages on the trending-tags.php filter [data-per-page]
function buildJsonURL(perPage){
var jsonUrl = aa_opt.jsonUrl,
ccategoryId = $('input.aa-current-category').val();
if (typeof(perPage) != 'undefined' && perPage != null){
jsonUrl += '?per_page='+perPage;
}
if (typeof(ccategoryId) != 'undefined' && ccategoryId != null && ccategoryId != ''){
jsonUrl += '&categories='+ccategoryId;
}
return jsonUrl;
}
// Function to update the currently loaded posts.
function postsInview() {
var postsInView = $('.aa-three-column-flex > a.aa-article').length;
return postsInView;
}
// Function to remove the error message
function removeError() {
$('.failed').remove();
}
$('.aa-recent-posts-wrapper').each(function(){
// 1. Create all the required variables
var $this = $(this),
recentPostsWrapper = $this,
sortFilter = $this.find('.aa-sorting-radio'),
termFilter = $this.find('.aa-post-filter'),
loadMore = $this.find('.aa-loadmore'),
recentPosts = $this.find('.recent-posts'),
perPage = termFilter.data('per-page'),
requestRunning = false,
count = 2; // set the initial new page for the load more button to 2
// 2. Term filter click event
// User clicks on the filters OR the load more button
recentPostsWrapper.on('click', '.aa-loadmore, .aajax-filter, .aa-sortby', function(e){
/*
3. Some resets
*/
e.preventDefault();
// If the loadmore is showing the loading icon, remove it.
$('.aa-loadmore.loading').removeClass('loading');
// Exit if request is already running
if (requestRunning) {return;}
requestRunning = true;
/**
* Language Variations set in theme options
* Get the current posts language choices for the article grid
*/
var datePosted = $('.aa-article:first .date-posted-on').text(),
readMore = $('.aa-article:first .aa-read-more').text();
/**
* Create our comparison from the initially clicked element.
* Using this to apply jQuery to elements depending on if the FILTER or the LOAD MORE BUTTON is clicked.
*/
var $this = $(this);
if ($this.hasClass('aajax-filter')) {
var niceTitle = 'Filter', // Title used for console.log
currentClick = 'filter-clicked';
}
if ($this.hasClass('aa-loadmore')) {
var niceTitle = 'Load More',
currentClick = 'loadmore-clicked';
}
if ($this.hasClass('aa-sortby')) {
var niceTitle = 'Sort-By',
currentClick = 'sort-clicked',
sortBy = $this.data('param'); // Get the hidden input data attr
}
console.log(niceTitle+' Clicked');
removeError();
// Check for filter or sort clicks
if (currentClick == 'filter-clicked' || currentClick == 'sort-clicked') {
// Remove current articles from the articles list to append requested articles later
var post_container_height = recentPosts.outerHeight();
recentPostsWrapper.css('minHeight', post_container_height).addClass('loading'); // Update the height of the container so it doesn't jump
recentPosts.fadeOut(300, function(){
recentPosts.find('.aa-article').remove(); // Fade out the recent posts and remove them from the page
});
loadMore.attr('data-page', 2); // Set the load more buttons attibute back to 2
/**
* Build the json AJAX call URL
* This gets updated within the ajax call by setting a hidden
* input field value with the current Json url
*/
var jsonUrl = buildJsonURL(perPage); // Get the Json url and ammount per page
var currentFilter = $(this);
// log the fetched url
console.log('Filter Json URL: '+jsonUrl);
/**
* Grab the current filters tag ID
*/
if (currentClick == 'filter-clicked') {
// Collect current filter data and toggle active class
var currentFilterLink = currentFilter.attr('href'),
currentFilterID = currentFilter.data('filter-id');
currentFilter.parent().addClass('active').siblings().removeClass('active'); // Toggle the active state
$('.aa-sortby').removeClass('active');
$('.aa-sortby:first').addClass('active');
if (typeof(currentFilterID) != 'undefined' && currentFilterID != null){
var setTags = '&tags='+currentFilterID;
jsonUrl += setTags; // Update the current Json url with the clicked tag_id
}
}
/**aa-current-tag_id
* Grab the sorting element type
*/
if (currentClick == 'sort-clicked') {
var currentTagId = $('.aa-current-tag_id').val();
$(this).addClass('active').siblings().removeClass('active'); // Toggle the active state
if (typeof(currentTagId) != 'undefined' && currentTagId != null && currentTagId != '') {
jsonUrl += currentTagId;
}
var hiddenRequestUrl = $('input.aa-request-url').val();
jsonUrl += sortBy;
}
}
// Check for loadmore clicks and create our NEW jsonUrl for the CURRENT page request
if (currentClick == 'loadmore-clicked') {
count++;
loadMore.addClass('loading');
var hiddenRequestUrl = $('input.aa-request-url').val(),
currentPage = loadMore.attr('data-page');
jsonUrl = hiddenRequestUrl+'&page='+currentPage;
console.log('Load more - Json URL: '+hiddenRequestUrl+'&page='+currentPage);
}
console.log('Passed - JSON url: '+jsonUrl);
// 4. finally send the Ajax request
$.ajax({
dataType: 'json',
url:jsonUrl
})
.done(function(response, status, request){
var perPage = $('.aa-post-filter').data('per-page'), // get the perpage items (default 6)
totalPosts = request.getResponseHeader('X-WP-Total'), // get the total posts
totalPages = request.getResponseHeader('X-WP-TotalPages'), // get the total pages
totalPostsContainer = $('.aa-total-posts'),
currentPostCountNum = totalPostsContainer.find('.current-post-count'),
totalPostsNum = totalPostsContainer.find('.total-posts'),
loadMoreButton = $('.load-more-wrapper');
loadMoreButton.show(); // Show the load more button
console.log('Initial total posts for current terms: '+totalPosts);
console.log('Initial total pages or current posts: '+totalPages);
/**
* Check to see if the posts in view exceed the <div class="aa-post-filter" data-per-page="6"></div>
* if they do reduce the perPage variable to totalPost number
*/
console.log('Original perPage var: '+perPage);
var perPage = (perPage > totalPosts) ? totalPosts : perPage;
console.log('Updated perPage var: '+perPage);
/**
* Add the current json URL and total pages available
* to the hidden fields in post-loop.php.
* Hidden fields are used to populate the load more content
*/
if (currentClick == 'filter-clicked' || currentClick == 'sort-clicked') {
if (currentClick == 'filter-clicked') {
// We need to add in the tag ID to a hidden input
// This is so we can grab this if they sort the posts by new or most popular
$('input.aa-current-tag_id').val(setTags);
}
$('input.aa-request-url').val(jsonUrl); // update the current json url
$('input.aa-total-pages').val(totalPages); // update the pages available
currentPostCountNum.empty().text(perPage); // Update the posts in view count text
totalPostsNum.empty().text(totalPosts); // Update the total posts count
}
// Check the total pages value from the input and hide the load more if no more posts available
if (totalPages <= 1) {
loadMoreButton.hide();
}
// If success loop with each response (post) object and create output
var output = '';
$.each(response,function(index,object){
// If this is the first item loaded add an ID to scroll it to the top
if (index === 0) {
output += '<a id="aa-scrolltoTop" class="aa-article '+object.pure_taxonomies.categories[0].slug+'" href="'+object.link+'">';
} else {
output += '<a class="aa-article '+object.pure_taxonomies.categories[0].slug+'" href="'+object.link+'">';
}
if (typeof(object.fields.header_image) != 'undefined'){ // Custom field Header Image
if ( '' != object.fields.header_image.sizes.thumbnail){ // Custom field Header Image
output += '<div class="aa-post-image b-lazy" style="background-image: url('+object.fields.header_image.sizes.thumbnail+')"></div>';
}
} else if ( '' != object.featured_image_url ) { // Featured Image
output += '<div class="aa-post-image b-lazy" style="background-image: url('+object.featured_image_url+')"></div>';
}
output +='<div class="aa-post-excerpt">';
if ( '' != object.title.rendered ){ // Post title
output +='<h2 class="h5">';
output += object.title.rendered;
output +='</h2>';
}
output +='<span class="date-label">';
output +='<span class="date-posted-on">'+datePosted+'</span>';
output += new Date(object.date).toLocaleDateString(); // convert the json date
output +='</span>';
output +='<div class="aa-read-more">';
output +=readMore; // Read more text set in theme and functions
output +='</div>';
output +='</div>';
output +='</div>';
output += '</a>';
});
// If output is ready append new posts
if (output.length) {
if (currentClick == 'filter-clicked' || currentClick == 'sort-clicked') {
setTimeout(function() {
// Append the posts
recentPosts.append(output)
.fadeIn(300);
// Reset the min-height to a single post height
recentPostsWrapper.css('minHeight', '285px').removeClass('loading');
}, 300);
}
if (currentClick == 'loadmore-clicked') {
$('.aa-loadmore').removeClass('loading');
loadMore.attr("data-page", count); // Step the page count
// Append the posts
recentPosts.append(output)
.fadeIn(300);
var visiblePosts = postsInview();
// Update the posts currently loaded number.
currentPostCountNum.empty().text(visiblePosts);
// Hide the button if we're showing all the posts.
if (visiblePosts >= totalPosts) {
loadMoreButton.hide();
console.log('visible posts more than total posts');
}
// Scroll the new posts into view and remove the scroll-to div
$('html, body').animate({
scrollTop: $("#aa-scrolltoTop").offset().top - 150
}, 300, function() {
setTimeout(function() {
$('#aa-scrolltoTop').attr('id','');
}, 1200);
});
}
console.log(niceTitle+' Complete!');
}
})
.fail(function(response){
// If fail log our error message
console.log('%cERROR: '+response.responseJSON.message, 'color: red;');
// Show the user an error message
var failed = '';
failed += '<div class="failed" style="min-width: 100%; text-align: center;">';
failed += '<img src="'+aa_opt.warningImageUrl+'" alt="Something went wrong!" height="15">';
failed += aa_opt.errorMessage;
failed += '</div>';
recentPosts.append(failed);
})
.always(function(response){
console.log('%cAll Requests Completed.\n-----------------------', 'color: green;');
// Always reset the requestRunning to keep sending new AJAX requests
requestRunning = false;
});
return false;
});
});
/** End $.ajax */
})(jQuery);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment