mackebryrsig
9/14/2017 - 7:28 AM

WordPress Ajax load more posts

WordPress Ajax load more posts

ajaxPosts : {
            init : function() {

                var scope = this;

                $('#load-more-posts').on( 'click', function() {
                    scope.loadPosts();
                });

            },
            loadPosts : function() {

                var content = $('#post-list'),
                    loader = $('#load-more-posts'),
                    cat = loader.data('category'),
                    ppp = 3,
                    offset = content.find('.post').length;

                if (!(loader.hasClass('post_loading_loader') || loader.hasClass('post_no_more_posts'))) {
            		$.ajax({
            			type: 'POST',
            			dataType: 'html',
            			url: ajax_load_posts.ajaxurl,
            			data: {
            				'ppp': ppp,
            				'offset': offset,
                            'category': cat,
            				'action': 'sqlservice_ajax_posts'
            			},
            			beforeSend : function () {
            				loader.addClass('post_loading_loader').html(ajax_load_posts.fetching);
            			},
            			success: function (data) {
                            var data = $(data);
            				if (data.length) {

                                var newPosts = data;

                                $(newPosts).css('opacity', 0);
            					content.append(newPosts);
                                $(newPosts).animate({ opacity: 1 });
            					loader.removeClass('post_loading_loader').html(ajax_load_posts.loadmore);
            				} else {
            					loader.removeClass('post_loading_loader').addClass('post_no_more_posts').html(ajax_load_posts.noposts);
            				}
            			},
            			error : function (jqXHR, textStatus, errorThrown) {
            				loader.html($.parseJSON(jqXHR.responseText) + ' :: ' + textStatus + ' :: ' + errorThrown);
                            loader.addClass('post_loading_loader').html(ajax_load_posts.errorText);
            				console.log(jqXHR);
            			},
            		});
            	}
            	offset += ppp;
            	return false;
            }
        },