Ajax Based Load More with Tax Query & Date Query
- سُلَيْمَان بْن دَاوُوْد

- Mar 31, 2023
- 3 min read
Updated: Apr 14, 2024
Here is the plugin code file.
<?php
/**
* Plugin Name: Solar IPS News Filter
* Plugin URI:
* Description: The plugin is used to filter news based on category and archives via AJAX.
* Version: 1.0
* Author: Independent Power
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
add_action('wp_ajax_get_news','get_news_callback');
add_action('wp_ajax_nopriv_get_news','get_news_callback');
function get_news_callback(){
/*
<pre>Array
(
[action] => get_news
[category] => 3
[archiveyear] => 2023
[searchtext] => sdfsdf
[pageno] => 1
)
*/
$category = sanitize_text_field($_POST['category']);
$archiveyear = sanitize_text_field($_POST['archiveyear']);
$searchtext = sanitize_text_field($_POST['searchtext']);
$paged = sanitize_text_field($_POST['pageno']);
$tax_query = array();
$date_query= array();
if($category){
array_push($tax_query,
array(
'taxonomy' => 'category',
'terms' => $category,
'field' => 'term_id',
)
);
}
if($archiveyear){
array_push($date_query,
array(
'year' => trim($archiveyear),
)
);
}
$args = array(
'post_type' => 'post',
'posts_per_page' => 10,
'post_status' => 'publish',
'paged' => $paged,
'tax_query' => $tax_query,
'date_query' => $date_query,
's' => $searchtext
);
if( empty($category) ) {
unset($args['tax_query']);
}
if( trim($archiveyear) =='' ) {
unset($args['date_query']);
}
if( $searchtext =='' ) {
unset($args['s']);
}
$loop = new WP_Query( array_filter($args) );
if($loop->have_posts()){
while ($loop->have_posts()){
$loop->the_post();
$totalpost = $loop->found_posts;
if ( has_post_thumbnail() ) {
$thumb_id = get_post_thumbnail_id();
$thumb_url = wp_get_attachment_image_src( $thumb_id, 'full' );
$thumb_alt = get_post_meta( $thumb_id, '_wp_attachment_image_alt', true );
$image = '<img src="'.esc_url( $thumb_url[0] ).'" alt="'.esc_attr( $thumb_alt ).'" class="img-full" />';
}else{
$image = '<img src="https://dummyimage.com/678x533/000/fff.jpg&text=No+Image" alt="Dummy Image" class="img-full" />';
}
$posts.=
'<a href="'.get_the_permalink().'" class="gl-content-card-comp text-white" data-aos="fade-up">
<div class="card-img">'.$image.'</div>
<div class="card-text">
<div class="meta-box">
<p class="date fw-b body-xs">'.get_the_date( "j F Y" ).'</p>
<h5>'.get_the_title().'</h5>
</div>
<ul class="cat-box">'.getcategorynameallinpost(get_the_ID()).'</ul>
</div>
</a>';
}
}else{
$posts.=
'<div class="notfoundmatter" data-aos="fade-up">
<p>Sorry, there are no matching blogs at this time. If you would like more information, you can contact us at <a href="tel:303-443-0115">303-443-0115</a>. Thank you!</p>
</div>';
}
echo json_encode( array( 'posts'=>base64_encode($posts), 'total' => $totalpost ) ) ;
wp_die();
}
function news_filter_js() {
wp_register_script('newsfilter-js',plugin_dir_url( __FILE__ ) . '/js/solarips-news.js',['jquery'],'',true);
$solarips = array(
'siteurl' => site_url(),
'adminurl' => admin_url(),
'ajaxurl' => admin_url('admin-ajax.php'),
'templateurl' => get_template_directory_uri()
);
wp_localize_script( 'newsfilter-js', 'solarips', $solarips );
wp_enqueue_script( 'newsfilter-js');
}
add_action( 'wp_enqueue_scripts', 'news_filter_js' );Here is the JS code file.
jQuery( document ).ready(function() {
jQuery("#archive").prepend("<option value='' selected='selected' disabled>Filter By</option>");
var pathname = window.location.pathname;
var pageSlug = pathname.split('/').pop();
if('news' == pageSlug){
var category = jQuery('#category').find(":selected").attr('data-termid');
var archiveyear = jQuery('#archive').find(":selected").text();
var searchtext = jQuery('#searchtext').val();
var pageno = jQuery('#pageno').val();
get_news(category, archiveyear, searchtext, pageno);
}
jQuery('.getnews').change(function(){
jQuery('#pageno').val(1);
var category = jQuery('#category').find(":selected").attr('data-termid');
var archiveyear = jQuery('#archive').find(":selected").text();
var searchtext = jQuery('#searchtext').val();
var pageno = jQuery('#pageno').val();
get_news(category, archiveyear, searchtext, pageno);
});
jQuery(document).keydown(function(e) {
if (e.keyCode == 13) {
jQuery('#pageno').val(1);
var category = jQuery('#category').find(":selected").attr('data-termid');
var archiveyear = jQuery('#archive').find(":selected").text();
var searchtext = jQuery('#searchtext').val();
var pageno = jQuery('#pageno').val();
get_news(category, archiveyear, searchtext, pageno);
}
});
jQuery('#loadmore').click(function(e) {
var category = jQuery('#category').find(":selected").attr('data-termid');
var archiveyear = jQuery('#archive').find(":selected").text();
var searchtext = jQuery('#searchtext').val();
var pageno = jQuery('#pageno').val();
get_news(category, archiveyear, searchtext, pageno);
});
jQuery('#clearall').click(function(e) {
jQuery('select').prop('selectedIndex', 0);
jQuery('#searchtext').val('');
jQuery('#pageno').val('1');
var category = jQuery('#category').find(":selected").attr('data-termid');
var archiveyear = jQuery('#archive').find(":selected").text();
var searchtext = jQuery('#searchtext').val();
var pageno = jQuery('#pageno').val();
get_news(category, archiveyear, searchtext, pageno);
});
function get_news($category, $archiveyear, $searchtext, $pageno){
var category = jQuery('#category').find(":selected").attr('data-termid');
var archiveyear = jQuery('#archive').find(":selected").text();
var searchtext = jQuery('#searchtext').val();
var pageno = jQuery('#pageno').val();
let
data = {
action : 'get_news',
category : category,
archiveyear : archiveyear,
searchtext : searchtext,
pageno : pageno
}
jQuery.ajax({
url : solarips.ajaxurl,
type : 'POST',
data : data,
beforeSend: function() {
},
success: function(response) {
var result = JSON.parse( response );
if(pageno > 1){
jQuery('.getnewsfeeds').append( decodeURIComponent(escape(window.atob(result.posts) )));
}else{
jQuery('.getnewsfeeds').empty().html( decodeURIComponent(escape(window.atob(result.posts) )));
}
jQuery('#pageno').val( parseInt(jQuery('#pageno').val()) +1 );
var count = jQuery('.getnewsfeeds a').length;
console.log('Total Record:'+result.total);
console.log('Visible Record:'+count);
if(count == result.total){
jQuery('#loadmore').show();
jQuery('#loadmore').text('No More Posts');
jQuery('#loadmore').css({'pointer-events':'none'});
}else if(result.total == null){
jQuery('#loadmore').hide();
}else{
jQuery('#loadmore').show();
jQuery('#loadmore').text('Load More');
jQuery('#loadmore').css({'pointer-events':'all'});
}
}
});
}
});Here is the HTML
<section class="grid-card-content-sec colm2 py">
<div class="container sm">
<div class="gl-drpdwnFilter-comp" data-aos="fade-up">
<h3>Recent News</h3>
<div class="drpdown-list">
<div class="form-group">
<?php
$categories = get_categories( array(
'orderby' => 'name',
'order' => 'ASC',
'parent' => 0,
'exclude' => 1
) );
?>
<select class="form-control getnews" id="category">
<option disabled selected value="">Category</option>
<?php $i=1; foreach($categories as $category){ ?>
<option data-termid="<?php echo $category->term_id; ?>" value="<?php echo $category->slug; ?>"><?php echo $category->name; ?></option>
<?php $i++; } ?>
</select>
<?php $my_archives = '<select id="archive" class="form-control getnews">' . wp_get_archives( array(
'type' => 'yearly',
'limit' => 50,
'echo' => 0,
'format' => 'option', // this outputs an <option>
) ) . '</select>'; echo $my_archives; ?>
<input type="search" placeholder="Search" class="form-control hasIcon" id="searchtext">
<div class="btn-box">
<a id="clearall" href="javascript:void(0);" class="ips-btn no-arrow">Clear All</a>
</div>
</div>
</div>
</div>
<div class="flex content-row getnewsfeeds">
</div>
<div class="load-more text-center mt-md" data-aos="fade-up">
<a href="javascript:void(0);" class="ips-btn cyan border" id="loadmore">Load More</a>
<input type="hidden" name="pageno" id="pageno" value="1">
</div>
</div>
</section>
Comments