Load More Posts Ajax Button in Woocommerce

Attempting to integrate this nice tutorial from @dingo_d into a Woocommerce archive-product.php template. Here’s what I’ve got so far:

archive-product.php

Read More

Added $cat_id under get_header

get_header( 'shop' ); 
$cat_id = get_query_var('cat');

Wrapped the loop with div

 <main id="main" class="site-main ajax_posts" role="main">
 <?php woocommerce_product_loop_start(); ?>
 ...
 <?php woocommerce_product_loop_end(); ?>
 </main><!-- /#main -->

pagination.php

the template file being overridden by my theme with the woocommerce pagination commented out

 <div id="more_posts" data-category="<?php echo esc_attr($cat_id); ?>"><?php esc_html_e('Load More', 'siiimple') ?></div>

 <!--<nav class="woocommerce-pagination">
<?php
    echo paginate_links( apply_filters( 'woocommerce_pagination_args', array(
        'base'         => esc_url_raw( str_replace( 999999999, '%#%', remove_query_arg( 'add-to-cart', get_pagenum_link( 999999999, false ) ) ) ),
        'format'       => '',
        'add_args'     => false,
        'current'      => max( 1, get_query_var( 'paged' ) ),
        'total'        => $wp_query->max_num_pages,
        'prev_text'    => '&larr;',
        'next_text'    => '&rarr;',
        'type'         => 'list',
        'end_size'     => 3,
        'mid_size'     => 3
    ) ) );
?>
 </nav>-->

functions.js

( function( $ ) {

//LOAD MORE

var $content = $('.ajax_posts');
var $loader = $('#more_posts');
var cat = $loader.data('category');
var ppp = 3;
var offset = $('#main').find('.post').length;

$loader.on( 'click', load_ajax_posts );

function load_ajax_posts() {
if (!($loader.hasClass('post_loading_loader') ||      
$loader.hasClass('post_no_more_posts'))) {
    $.ajax({
        type: 'POST',
        dataType: 'html',
        url: screenReaderText.ajaxurl,
        data: {
            'cat': cat,
            'ppp': ppp,
            'offset': offset,
            'action': 'mytheme_more_post_ajax'
        },
        beforeSend : function () {
            $loader.addClass('post_loading_loader').html('');
        },
        success: function (data) {
            var $data = $(data);
            if ($data.length) {
                var $newElements = $data.css({ opacity: 0 });
                $content.append($newElements);
                $loader.removeClass('post_loading_loader');
                $newElements.animate({ opacity: 1 });
                     $loader.removeClass('post_loading_loader').html(screenReaderText.loadmore);
            } else {
                $loader.removeClass('post_loading_loader').addClass('post_no_more_posts').html(screenReaderText.noposts);
            }
        },
        error : function (jqXHR, textStatus, errorThrown) {
            $loader.html($.parseJSON(jqXHR.responseText) + ' :: ' + textStatus + ' :: ' + errorThrown);
            console.log(jqXHR);
        },
    });
}
offset += ppp;
return false;
 }

 //LOAD MORE


 } )( jQuery );

functions.php

Placed at bottom of functions.php

 // LOAD MORE
    $ajaxurl = '';
    if( in_array('sitepress-multilingual-cms/sitepress.php', get_option('active_plugins')) ){
    $ajaxurl .= admin_url( 'admin-ajax.php?lang=' . ICL_LANGUAGE_CODE );
    } else{
    $ajaxurl .= admin_url( 'admin-ajax.php');
    }
    // END LOAD MORE


    wp_localize_script( 'twentysixteen-script', 'screenReaderText', array(
        'expand'   => __( 'expand child menu', 'siiimple' ),
        'collapse' => __( 'collapse child menu', 'siiimple' ),

        //LOAD MORE
        'ajaxurl'  => $ajaxurl,
        'noposts'  => esc_html__('No older posts found', 'siiimple'),
        'loadmore' => esc_html__('Load more', 'siiimple')
        // END LOAD MORE
 ) );

 //LOAD MORE
 add_action('wp_ajax_nopriv_mytheme_more_post_ajax',  'mytheme_more_post_ajax');
 add_action('wp_ajax_mytheme_more_post_ajax', 'mytheme_more_post_ajax');

 if (!function_exists('mytheme_more_post_ajax')) {
function mytheme_more_post_ajax(){

    $ppp     = (isset($_POST['ppp'])) ? $_POST['ppp'] : 3;
    $cat     = (isset($_POST['cat'])) ? $_POST['cat'] : 0;
    $offset  = (isset($_POST['offset'])) ? $_POST['offset'] : 0;

    $args = array(
        'post_type'      => 'product',
        'posts_per_page' => $ppp,
        'cat'            => $cat,
        'offset'          => $offset,
    );

    $loop = new WP_Query($args);

    $out = '';

    if ($loop -> have_posts()) :
        while ($loop -> have_posts()) :
            $loop -> the_post();

            $category_out = array();
            $categories = get_the_category();
            foreach ($categories as $category_one) {
                $category_out[] ='<a href="'.esc_url( get_category_link( $category_one->term_id ) ).'" class="'.strtolower($category_one->name).'">' .$category_one->name.'</a>';
            }
            $category_out = implode(', ', $category_out);

            $cat_out = (!empty($categories)) ? '<span class="cat-links"><span class="screen-reader-text">'.esc_html__('Categories', 'twentysixteen').'</span>'.$category_out.'</span>' : '';

            $out .= '<article id="post-'. get_the_ID().'" class="'. implode(' ', get_post_class()) .'">
                        <header class="entry-header">';
                    $out .= '<h2 class="entry-title"><a href="'.esc_url( get_permalink() ).'" rel="bookmark">'.get_the_title().'</a></h2>';
                $out .= '</header>'.
                    '</article>';

        endwhile;
    endif;

    wp_reset_postdata();

    wp_die($out);
  }
 }
 //END LOAD MORE

That’s it. Don’t think I’m missing anything…Thanks!

Related posts

Leave a Reply