Ask your WordPress questions! Pay money and get answers fast! Comodo Trusted Site Seal
Official PayPal Seal

Load more button AJAX WordPress

  • SOLVED

Hello there guys. I'm in need of a hand with some JS issue.

My load more button is supposed to display the rest of galleries on the page but it is not working

http://readyluck.com/portfolio/

Here is my php:

<main id="gallery-list" class="container">

<?php
$loop = new WP_Query(array(
'post_type' => 'gallery',
'posts_per_page' => 16,
'orderby' => 'date',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'hide_from_portfolio_page',
'compare' => 'NOT EXISTS'
),
array(
'key' => 'hide_from_portfolio_page',
'value' => '0',
'compare' => '='
)
)
));
while ( $loop->have_posts() ) : $loop->the_post();

if ($loop->current_post % 2 == 0) {
$image = get_field('landscape_cover_image')['sizes']['travel'];
$orientation = 'landscape';
}else{
$image = get_field('portrait_cover_image')['sizes']['photographer-portrait'];
$orientation = 'portrait';
}
$photographer = get_field('photographer');
$permalink = get_permalink($photographer);
$name = get_the_title($photographer);
$slug = get_post_field('post_name', $photographer);
?>
<div class="post <?php echo $slug; ?>" data-gallery="#<?php echo get_post_field('post_name') ?>">
<div class="image <?php echo $orientation; ?>">
<div class="post-img" style="background-image:url('<?php echo $image ?>')"></div>
<div class="text-overlay">
<div class="text-container">
<h2><a href="#<?php echo get_post_field('post_name') ?>"><?php the_title(); ?></a></h2></h2>
<p>By <a href="<?php echo $permalink; ?>"><?php echo $name; ?></a></p>
</div>
</div>
</div>
</div>

<?php endwhile; ?>
<div class="load-more-list"></div>
<a class="button" id="gallery-load-more">Load More</a>
</main>


Here is my function in functions.php:

/* GALLERY LOAD MORE
================================================= */
function get_gallery() {

if ( isset($_REQUEST) ) {
$offset = $_REQUEST['offset'];
}

$params = array(
'posts_per_page' => 15,
'post_type' => 'gallery',
'offset' => 15,
'orderby' => 'date',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'hide_from_portfolio_page',
'compare' => 'NOT EXISTS'
),
array(
'key' => 'hide_from_portfolio_page',
'value' => '0',
'compare' => '='
)
)
);

// The Query
$the_query = new WP_Query( $params );

if ($loop->current_post % 2 == 0) {
$image = get_field('landscape_cover_image')['sizes']['travel'];
$orientation = 'landscape';
}else{
$image = get_field('portrait_cover_image')['sizes']['photographer-portrait'];
$orientation = 'portrait';
}
$photographer = get_field('photographer');
$permalink = get_permalink($photographer);
$name = get_the_title($photographer);
$slug = get_post_field('post_name', $photographer);
?>
<div class="post <?php echo $slug; ?>" data-gallery="#<?php echo get_post_field('post_name') ?>">
<div class="image <?php echo $orientation; ?>">
<div class="post-img" style="background-image:url('<?php echo $image ?>')"></div>
<div class="text-overlay">
<div class="text-container">
<h2><a href="#<?php echo get_post_field('post_name') ?>"><?php the_title(); ?></a></h2></h2>
<p>By <a href="<?php echo $permalink; ?>"><?php echo $name; ?></a></p>
</div>
</div>
</div>
</div>

<?php

wp_reset_postdata();

die('');
}
add_action( 'get_wp_ajax_gallery', 'get_gallery' );
add_action( 'get_wp_ajax_nopriv_gallery', 'get_gallery' );


Here is my js file:

jQuery(document).ready(function($){

// Masonry
$('#gallery-list').masonry({
itemSelector: '.post',
columnWidth: 370,
gutter: 30,
animationOptions: {
duration: 1200,
easing: 'swing'
}
});

function doMasonry(val) {
group_class = "." + val;

if(val != "") {
$(".post").hide();
$(group_class).show();
$('#gallery-list').masonry();
} else {
$(".post").show();
$('#gallery-list').masonry();
}
}

// Filter
$('#gallery-filter select').selectric({
labelBuilder: '<span class="label-pre">Photographer —</span> {text}',
onRefresh: function(element){
doMasonry( $(element).val() )
},
onChange: function(element){
doMasonry( $(element).val() )
}
});

if ( $('#gallery-filter') ) {
var photog = $('#gallery-filter').data('photog')
var options = new Array()
$('.selectric-items ul li').each(function(){
var index = $(this).data('index')
var val = $(this).html()
val = val.replace(/\s+/g, '-').toLowerCase()

options[val] = index
})
$('#gallery-filter select').prop('selectedIndex', options[photog]).selectric('refresh');
$('#gallery-list').masonry();
}

// Check to see if a gallery should be open when the page is loaded
checkUrl();

// Open gallery
$('#gallery-list .post, #page-overview #galleries .post').on('click', function(e){
e.preventDefault();

// Get hash
var gallery = $(this).data('gallery');

// Open gallery
openGallery(gallery);
})

// Close gallery
$('#gallery-close').on('click', function(e){
e.preventDefault();

// Remove from URL
removeHash();

// Purge lightbox
purgeGallery();

// Hide lightbox
$('#gallery-window').hide();

// Re-introduce page scroll
$('#page-gallery').removeClass('gallery-window-open');
})

// Functions
function checkUrl() {
var hash = window.location.hash;

// If the URL contains a gallery reference, attempt to open it
if(hash){
// Open gallery
openGallery(hash);
}
}
function openGallery(hash) {
// Add to URL
window.location.hash = hash;

// Populate lightbox
getGallery(hash);

// Open lightbox
$('#gallery-window').show();

// Prevent page scroll
$('#page-gallery').addClass('gallery-window-open');
}
function purgeGallery() {
$('#gallery-window .gallery-window-count').html('').hide();
$('#gallery-window .gallery-window-title').html('').hide();
$('#gallery-window .gallery-window-photographer a').html('').attr('href', '').parent().hide();
$('#gallery-slideshow').slick('unslick');
$('#gallery-slideshow').html('');
}
function getGallery(hash) {

var slug = hash.substr(1);

var gallery = $('#gallery-window').data('root') + '/portfolio/' + slug;

$.ajax({
type : 'POST',
url : gallery,
dataType : 'json'
})
.done(function(data) {
var title = data['title'];
var photographer = data['photographer'];
var images = data['images'];
var permalink = data['permalink'];
var imageCount = Object.keys(images).length;
var i = 0;

// Apply text to window
$('#gallery-window .gallery-window-title').html(title).fadeIn();
$('#gallery-window .gallery-window-photographer a').html(photographer).attr('href', permalink).parent().fadeIn();
$('#gallery-window .gallery-window-count').html('<span>1</span>/' + imageCount).fadeIn();

// Add images to window
loadImages(images);

$('#gallery-slideshow').on('beforeChange', function(e, slick, currentSlide, nextSlide){
var current = nextSlide+1;
$('#gallery-window .gallery-window-count span').html(current);

});
});
}
function removeHash () {
var scrollV, scrollH, loc = window.location;
if ("pushState" in history)
history.pushState("", document.title, loc.pathname + loc.search);
else {
// Prevent scrolling by storing the page's current scroll offset
scrollV = document.body.scrollTop;
scrollH = document.body.scrollLeft;

loc.hash = "";

// Restore the scroll offset, should be flicker free
document.body.scrollTop = scrollV;
document.body.scrollLeft = scrollH;
}
}
function objectLength (object) {
var length = 0;
for( var key in object ) {
if( object.hasOwnProperty(key) ) {
++length;
}
}
return length;
}
function loadImage (iterator, image, images, count) {
if (image) {
var alt = image["alt"]
var url = image["url"]
var img = new Image();
img.style.display = "none";
img.onload = function(e) {
$(this).fadeIn(300).parent().removeClass('loading');
iterator++;
if (iterator <= count) {
loadImage(iterator, images[iterator], images, count);
}
};
$('#gallery-slideshow .image-' + iterator).html(img)
img.src = url;
img.alt = alt;
}
}
function loadImages (images) {
var count = objectLength(images);
// Create slides
var i = 0;
images.forEach( function(e) {
$('#gallery-slideshow').append('<div class="loading slide image-' + i + '"></div>');
i++;
});
activateSlick();

// Load images synchronously
loadImage (0, images[0], images, count);
}
function activateSlick () {
$('#gallery-slideshow').slick({
infinite: false,
variableWidth: true,
speed: 350,
slidesToShow: 1,
focusOnSelect: true,
centerMode: true,
responsive: [
{
breakpoint: 1024,
settings: {
centerMode: false
}
}],
prevArrow: '<button type="button" class="slick-prev">&#59650;</button>',
nextArrow: '<button type="button" class="slick-next">&#59649;</button>'
});
}
$('#gallery-load-more').on("click",function(e){
get_gallery();

e.preventDefault();
});

});




Thanks a lot in advance!

Richard

Answers (4)

2018-02-08

Reigel Gallarde answers:

you have javascript error on your page... you have to fixed this first.


richard_b comments:

Hi Reigel, thanks for replying.

I'm aware of the error --. get_gallery is not defined.

I just don't know how to fix it.

Thanks


Reigel Gallarde comments:

was this working before?


richard_b comments:

I'm not sure, it may not have been completed but it seems complete to me.

I still can't get it to work.

2018-02-08

Arnav Joy answers:

why you don't try this plugin
https://wordpress.org/plugins/ajax-load-more/

it is very good and easy to use.

2018-02-08

Krishna Tiwari answers:

HI
Please following change in you code find & replace:
add_action( 'get_wp_ajax_gallery', 'get_gallery' );
add_action( 'get_wp_ajax_nopriv_gallery', 'get_gallery' );

to

add_action( 'wp_ajax_get_gallery', 'get_gallery' );
add_action( 'wp_ajax_nopriv_get_gallery', 'get_gallery' );


richard_b comments:

Krishna, thanks a lot for your answer!

No errors now. Still not loading more posts ;-(

Mauricio

2018-02-08

Cuong Lai Dinh answers:

PHP:


<main id="gallery-list" class="container">

<?php
$loop = new WP_Query(array(
'post_type' => 'gallery',
'posts_per_page' => 16,
'orderby' => 'date',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'hide_from_portfolio_page',
'compare' => 'NOT EXISTS'
),
array(
'key' => 'hide_from_portfolio_page',
'value' => '0',
'compare' => '='
)
)
));
while ( $loop->have_posts() ) : $loop->the_post();

if ($loop->current_post % 2 == 0) {
$image = get_field('landscape_cover_image')['sizes']['travel'];
$orientation = 'landscape';
}else{
$image = get_field('portrait_cover_image')['sizes']['photographer-portrait'];
$orientation = 'portrait';
}
$photographer = get_field('photographer');
$permalink = get_permalink($photographer);
$name = get_the_title($photographer);
$slug = get_post_field('post_name', $photographer);
?>
<div class="post <?php echo $slug; ?>" data-gallery="#<?php echo get_post_field('post_name') ?>">
<div class="image <?php echo $orientation; ?>">
<div class="post-img" style="background-image:url('<?php echo $image ?>')"></div>
<div class="text-overlay">
<div class="text-container">
<h2><a href="#<?php echo get_post_field('post_name') ?>"><?php the_title(); ?></a></h2>
<p>By <a href="<?php echo $permalink; ?>"><?php echo $name; ?></a></p>
</div>
</div>
</div>
</div>

<?php endwhile; ?>
<div class="load-more-list"></div>
<a class="button" id="gallery-load-more">Load More</a>
</main>


Execute AJAX:


/* GALLERY LOAD MORE
================================================= */
function get_gallery() {

if ( isset( $_REQUEST ) ) {
$offset = $_REQUEST['offset'];
}

$params = array(
'posts_per_page' => 15,
'post_type' => 'gallery',
'offset' => 15,
'orderby' => 'date',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'hide_from_portfolio_page',
'compare' => 'NOT EXISTS'
),
array(
'key' => 'hide_from_portfolio_page',
'value' => '0',
'compare' => '='
)
)
);

// The Query
$loop = new WP_Query( $params );

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

if ( $loop->current_post % 2 == 0 ) {
$image = get_field( 'landscape_cover_image' )['sizes']['travel'];
$orientation = 'landscape';
} else {
$image = get_field( 'portrait_cover_image' )['sizes']['photographer-portrait'];
$orientation = 'portrait';
}
$photographer = get_field( 'photographer' );
$permalink = get_permalink( $photographer );
$name = get_the_title( $photographer );
$slug = get_post_field( 'post_name', $photographer );
?>
<div class="post <?php echo $slug; ?>" data-gallery="#<?php echo get_post_field( 'post_name' ) ?>">
<div class="image <?php echo $orientation; ?>">
<div class="post-img" style="background-image:url('<?php echo $image ?>')"></div>
<div class="text-overlay">
<div class="text-container">
<h2><a href="#<?php echo get_post_field( 'post_name' ) ?>"><?php the_title(); ?></a></h2>

<p>By <a href="<?php echo $permalink; ?>"><?php echo $name; ?></a></p>
</div>
</div>
</div>
</div>

<?php
endwhile;
wp_reset_postdata();
}

die();
}

add_action( 'get_wp_ajax_gallery', 'get_gallery' );
add_action( 'get_wp_ajax_nopriv_gallery', 'get_gallery' );


Javascript:


jQuery(document).ready(function ($) {
// Masonry
var galleryList = $('#gallery-list');
galleryList.masonry({
itemSelector: '.post',
columnWidth: 370,
gutter: 30,
animationOptions: {
duration: 1200,
easing: 'swing'
}
});

function doMasonry(val) {
var group_class = "." + val;

if (val != "") {
$(".post").hide();
$(group_class).show();
galleryList.masonry();
} else {
$(".post").show();
galleryList.masonry();
}
}

// Filter
var galleryFilter = $('#gallery-filter');
galleryFilter.find('select').selectric({
labelBuilder: '<span class="label-pre">Photographer —</span> {text}',
onRefresh: function (element) {
doMasonry($(element).val())
},
onChange: function (element) {
doMasonry($(element).val())
}
});

if (galleryFilter) {
var photog = galleryFilter.data('photog');
var options = [];
$('.selectric-items ul li').each(function () {
var index = $(this).data('index');
var val = $(this).html();
val = val.replace(/\s+/g, '-').toLowerCase();

options[val] = index
});
galleryFilter.find('select').prop('selectedIndex', options[photog]).selectric('refresh');
galleryList.masonry();
}

// Check to see if a gallery should be open when the page is loaded
checkUrl();

// Open gallery
$('#gallery-list .post, #page-overview #galleries .post').on('click', function (e) {
e.preventDefault();

// Get hash
var gallery = $(this).data('gallery');

// Open gallery
openGallery(gallery);
});

// Close gallery
$('#gallery-close').on('click', function (e) {
e.preventDefault();

// Remove from URL
removeHash();

// Purge lightbox
purgeGallery();

// Hide lightbox
$('#gallery-window').hide();

// Re-introduce page scroll
$('#page-gallery').removeClass('gallery-window-open');
});

// Functions
function checkUrl() {
var hash = window.location.hash;

// If the URL contains a gallery reference, attempt to open it
if (hash) {
// Open gallery
openGallery(hash);
}
}

function openGallery(hash) {
// Add to URL
window.location.hash = hash;

// Populate lightbox
getGallery(hash);

// Open lightbox
$('#gallery-window').show();

// Prevent page scroll
$('#page-gallery').addClass('gallery-window-open');
}

var galleryWindow = $('#gallery-window');
var galleryWindowCount = galleryWindow.find('.gallery-window-count'),
galleryWindowTitle = galleryWindow.find('.gallery-window-title'),
galleryWindowPhotographerLink = galleryWindow.find('.gallery-window-photographer a'),
gallerySlideshow = $('#gallery-slideshow');

function purgeGallery() {
galleryWindowCount.html('').hide();
galleryWindowTitle.html('').hide();
galleryWindowPhotographerLink.html('').attr('href', '').parent().hide();
gallerySlideshow.slick('unslick');
gallerySlideshow.html('');
}

function getGallery(hash) {

var slug = hash.substr(1);

var gallery = $('#gallery-window').data('root') + '/portfolio/' + slug;

$.ajax({
type: 'POST',
url: gallery,
dataType: 'json'
})
.done(function (data) {
var title = data['title'];
var photographer = data['photographer'];
var images = data['images'];
var permalink = data['permalink'];
var imageCount = Object.keys(images).length;

// Apply text to window
galleryWindowTitle.html(title).fadeIn();
galleryWindowPhotographerLink.html(photographer).attr('href', permalink).parent().fadeIn();
galleryWindowCount.html('<span>1</span>/' + imageCount).fadeIn();

// Add images to window
loadImages(images);

$('#gallery-slideshow').on('beforeChange', function (e, slick, currentSlide, nextSlide) {
var current = nextSlide + 1;
galleryWindowCount.find('span').html(current);

});
});
}

function removeHash() {
var scrollV, scrollH, loc = window.location;
if ("pushState" in history)
history.pushState("", document.title, loc.pathname + loc.search);
else {
// Prevent scrolling by storing the page's current scroll offset
scrollV = document.body.scrollTop;
scrollH = document.body.scrollLeft;

loc.hash = "";

// Restore the scroll offset, should be flicker free
document.body.scrollTop = scrollV;
document.body.scrollLeft = scrollH;
}
}

function objectLength(object) {
var length = 0;
for (var key in object) {
if (object.hasOwnProperty(key)) {
++length;
}
}
return length;
}

function loadImage(iterator, image, images, count) {
if (image) {
var alt = image["alt"];
var url = image["url"];
var img = new Image();
img.style.display = "none";
img.onload = function () {
$(this).fadeIn(300).parent().removeClass('loading');
iterator++;
if (iterator <= count) {
loadImage(iterator, images[iterator], images, count);
}
};
$('#gallery-slideshow').find('.image-' + iterator).html(img);
img.src = url;
img.alt = alt;
}
}

function loadImages(images) {
var count = objectLength(images);
// Create slides
var i = 0;
images.forEach(function () {
gallerySlideshow.append('<div class="loading slide image-' + i + '"></div>');
i++;
});
activateSlick();

// Load images synchronously
loadImage(0, images[0], images, count);
}

function activateSlick() {
gallerySlideshow.slick({
infinite: false,
variableWidth: true,
speed: 350,
slidesToShow: 1,
focusOnSelect: true,
centerMode: true,
responsive: [
{
breakpoint: 1024,
settings: {
centerMode: false
}
}],
prevArrow: '<button type="button" class="slick-prev">&#59650;</button>',
nextArrow: '<button type="button" class="slick-next">&#59649;</button>'
});
}

$('#gallery-load-more').on("click", function (e) {
getGallery();

e.preventDefault();
});

});


richard_b comments:

Thanks a lot Cuong but now I get this:

Uncaught TypeError: Cannot read property 'substr' of undefined
at o (all.min.js:6)
at HTMLAnchorElement.<anonymous> (all.min.js:6)
at HTMLAnchorElement.dispatch (all.min.js:2)
at HTMLAnchorElement.m.handle (all.min.js:2)


Any ideas?


Cuong Lai Dinh comments:

Please try this in click event:


$('#gallery-load-more').on("click", function (e) {
getGallery(window.location.hash);

e.preventDefault();
});


richard_b comments:

The error is now gone from the console but button is still not working.