Ajax Based Load More with Tax Query & Date Query

Ajax Based Load More with Tax Query & Date Query

Here is the plugin code file.

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 = ''.esc_attr( $thumb_alt ).'';
                
            }else{ 

                $image = 'Dummy Image';

            } 

    $posts.=
    '
        
'.$image.'

'.get_the_date( "j F Y" ).'

'.get_the_title().'
    '.getcategorynameallinpost(get_the_ID()).'
'; } }else{ $posts.= '

Sorry, there are no matching blogs at this time. If you would like more information, you can contact us at 303-443-0115. Thank you!

'; } 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("");


    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

Recent News

'name', 'order' => 'ASC', 'parent' => 0, 'exclude' => 1 ) ); ?> ' . wp_get_archives( array( 'type' => 'yearly', 'limit' => 50, 'echo' => 0, 'format' => 'option', // this outputs an

Leave a Reply

Your email address will not be published. Required fields are marked *