graylaurenm
8/21/2016 - 1:56 PM

Genesis infinite scroll, supporting column classes, custom settings by page, and both auto + button loading

Genesis infinite scroll, supporting column classes, custom settings by page, and both auto + button loading

jQuery(function($){

	$('.pagination').remove()

	var button = $('.content .load-more-auto');
	var page = 2;
	var loading = false;
	var maxpage = beloadmore.maxpage;
	var scrollHandling = {
	    allow: true,
	    reallow: function() {
	        scrollHandling.allow = true;
	    },
	    delay: 400 //(milliseconds) adjust to the highest acceptable value
	};
	var pageType = $('.load-more-auto').attr('id');
	var waiting = false;
	var done = false;
	var overMax = false;

	$(window).scroll(function(){ // differs
		if( ! done && ! loading && scrollHandling.allow && ! waiting ) { // differs
			scrollHandling.allow = false; // differs
			setTimeout(scrollHandling.reallow, scrollHandling.delay); // differs
			var offset = $(button).offset().top - $(window).scrollTop(); // differs
			if( 2000 > offset ) { // differs
				$(button).appendTo('.content');
				loading = true;
				$('.load-more-auto').fadeIn(1000);
				var data = {
					action: 'sn_infinite_scroll_ajax',
					nonce: beloadmore.nonce,
					page: page,
					pageType: pageType,
					query: beloadmore.query,
				};
				$.post(beloadmore.url, data, function(res) {
					if(res.success) {
						$('.load-more-auto').remove();
						$(res.data).hide().appendTo('.content').fadeIn(1000);
						page = page + 1;
						if( page >= maxpage ) {
							overMax = true;
						}
						if( overMax ) {
							$('.content').append( '<div class="fully-loaded">No more articles</div>' );
							waiting = true; // differs
							done = true;
						} else if ( page == 5 ) { // differs
							waiting = true;
						}
						loading = false;
						$('.load-more-auto').fadeOut(1000);
					} else {
						// console.log(res);
					}
				}).fail(function(xhr, textStatus, e) {
					// console.log(xhr.responseText);
				});

			}
		}
	});

	// Not "DRY" (see "differs")
	$('body').on('click', '.load-more-button', function(){ // differs
		if( ! loading ) { // differs
			$('.load-more-button').remove();
			$(button).appendTo('.content');
			loading = true;
			$(".load-more-auto").fadeIn(1000);
			var data = {
				action: 'sn_infinite_scroll_ajax',
				nonce: beloadmore.nonce,
				page: page,
				pageType: pageType,
				query: beloadmore.query,
			};
			$.post(beloadmore.url, data, function(res) {
				if(res.success) {
					$(res.data).hide().appendTo('.content').fadeIn(1000);
					page = page + 1;
					if( page >= maxpage ) {
						overMax = true;
					}
					if( overMax ) {
						$('.content').append( '<div class="fully-loaded">No more articles</div>' );
						done = true;
					} else { // differs
						waiting = false;
					}
					loading = false;
					$('.load-more-auto').fadeOut(1000);
				} else {
					// console.log(res);
				}
			}).fail(function(xhr, textStatus, e) {
				// console.log(xhr.responseText);
			});
		}
	});

});
<?php

/**
 *
 * Infinite Scroll
 *
 * @since 1.0.0
 *
 * @author Lauren Gray
 * @author Bill Erickson
 * @link http://www.billerickson.net/infinite-scroll-in-wordpress
 *
 * Use ajax to load additional articles upon user scroll.
 * After a set number of auto loads, stop until user
 * clicks on button to continue. Then auto load continually.
 * Support column classes and custom posts per page.
 *
 * Set up page for infinite scroll
 *
 */
add_action( 'genesis_after_loop', 'sn_infinite_scroll_support' );
function sn_infinite_scroll_support() {
	if ( ! is_singular() ) {
		if ( is_home() || is_front_page() ) {
			$determinePage = 'is-home';
		} else if ( is_category( 508 ) || is_category( 1551 ) ) {
			$determinePage = 'is-index';
		} else if ( is_archive() ) {
			$determinePage = 'is-archive';
		} else {
			$determinePage = 'is-else';
		}
		echo '<div class="load-more-auto" id="' . $determinePage . '"><i class="fa fa-spinner fa-spinner-hide fa-pulse fa-3x fa-fw"></i></div>';
	}
}

/**
 *
 * Infinite Scroll
 *
 * @since 1.0.0
 *
 * @author Lauren Gray
 * @author Bill Erickson
 * @link http://www.billerickson.net/infinite-scroll-in-wordpress
 *
 * Enqueue necessary JS file and localize.
 *
 */
add_action( 'wp_enqueue_scripts', 'sn_infinite_scroll_enqueue' );
function sn_infinite_scroll_enqueue() {

	if ( ! is_singular() ) {

		global $wp_query;

		$args = array(
			'nonce' => wp_create_nonce( 'be-load-more-nonce' ),
			'url'   => admin_url( 'admin-ajax.php' ),
			'query' => $wp_query->query,
			'maxpage' => $wp_query->max_num_pages,
		);
				
		wp_enqueue_script( 'sn-load-more', get_stylesheet_directory_uri() . '/assets/js/load-more.js', array( 'jquery' ), '1.0', true );
		wp_localize_script( 'sn-load-more', 'beloadmore', $args );

	}

}

/**
 *
 * Infinite Scroll
 *
 * @since 1.0.0
 *
 * @author Lauren Gray
 * @author Bill Erickson
 * @link http://www.billerickson.net/infinite-scroll-in-wordpress
 *
 * Parse information
 *
 */
add_action( 'wp_ajax_sn_infinite_scroll_ajax', 'sn_infinite_scroll_ajax' );
add_action( 'wp_ajax_nopriv_sn_infinite_scroll_ajax', 'sn_infinite_scroll_ajax' );
function sn_infinite_scroll_ajax() {

	if ( ! is_singular() ) {

		check_ajax_referer( 'be-load-more-nonce', 'nonce' );
	    
		$args = isset( $_POST['query'] ) ? array_map( 'esc_attr', $_POST['query'] ) : array();
		$args['post_type'] = isset( $args['post_type'] ) ? esc_attr( $args['post_type'] ) : 'post';
		$args['paged'] = esc_attr( $_POST['page'] );
		$args['post_status'] = 'publish';

		$pageType = esc_attr( $_POST['pageType'] );
		$page = esc_attr( $_POST['page'] );
		$done = esc_attr( $_POST['done'] );
		$overMax = esc_attr( $_POST['overMax'] );

		if ( $pageType == "is-home" ) {
			$initial = 7;
			$ppp = 6;
			$columns = 2;
			add_filter( 'genesis_post_info', 'sn_infinite_post_info' );
			add_filter( 'excerpt_length', 'sn_infinite_excerpt_length' );
		} else if ( $pageType == "is-index" ) {
			$initial = 12;
			$ppp = 12;
			if ( ! wp_is_mobile() ) {
				$columns = 4;
			} else {
				$columns = 2;
			}
		} else if ( $pageType == "is-archive" ) {
			$initial = 18;
			$ppp = 6;
			if ( ! wp_is_mobile() ) {
				$columns = 3;
			} else {
				$columns = 2;
			}
		} else {
			$initial = $posts_per_page;
			$ppp = $posts_per_page;
			$columns = 2;
		}
		$args['posts_per_page'] = $ppp;
		$args['offset'] = $initial + ( $ppp * ( $page - 2 ) );

		ob_start();

		$loop = new WP_Query( $args );
		if( $loop->have_posts() ): while( $loop->have_posts() ): $loop->the_post();
			sn_post_summary( $loop->current_post, $columns, $pageType );
		endwhile;
		endif;
		wp_reset_postdata();

		if ( $page == 4 && ! $done && ! $overMax ) {
			echo '<a class="load-more-button"><svg id="pagination-arrow-down" data-name="pagination-arrow-down" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 91.44 62.88"><polygon class="pagination-bg" points="91.44 41.96 47.27 62.88 3.55 41.96 3.55 3.54 91.44 3.54 91.44 41.96"/><polygon class="pagination-outline" points="88.39 38.91 44.23 59.83 0.5 38.91 0.5 0.5 88.39 0.5 88.39 38.91"/></svg><span>Load More</span></a>';
		}

		$data = ob_get_clean();

		wp_send_json_success( $data );
		wp_die();

	}

}

/**
 *
 * Infinite Scroll
 *
 * @since 1.0.0
 *
 * @author Lauren Gray
 * @author Bill Erickson
 * @link http://www.billerickson.net/infinite-scroll-in-wordpress
 *
 * Output articles
 *
 */
function sn_post_summary( $count, $columns, $pageType ) {
	
	// Be able to convert the number of columns to the class name in Genesis
	$fractions = array( '', 'half', 'third', 'fourth', 'fifth', 'sixth' );

	// Make a note of which column we're in
	$column_number = ( $count  % $columns ) + 1;

	// Add one-* class to make it correct width
	$countClasses = sprintf( 'one-' . $fractions[$columns - 1] . ' ', $columns );
	
	// Add a class to the first column, so we're sure of starting a new row with no padding-left
	if ( 1 == $column_number )
		$countClasses .= 'first ';

	echo '<article class="' . $countClasses . implode( ' ', get_post_class() ) . '">'; // add column class
	do_action( 'genesis_entry_header' );
	if ( $pageType != "is-index" && $pageType != "is-archive"  )
		do_action( 'genesis_entry_content' );
	echo '</article>';

}