I'm using AJAX to "Show More". Currently I have my custom post type show 12 initially and when the "Show More" button is clicked, 12 more post-types are loaded on page.
The Issue: After the first click, 12 are shown. But every click proceeding, it continues to repeat the previously populated 12 items.
Question: How can I properly use AJAX to show the posts, by 12s, when the users clicks "Show More".
AJAX Handler in Functions.php
function ajax_more_team($offset) {
$offset = $offset + 12;
header("Content-Type: text/html");
$args = array(
'suppress_filters' => true,
'post_type' => 'team',
'posts_per_page' => 12,
'offset' => $offset,
);
$the_query = new WP_Query($args);
if ($the_query -> have_posts()) : while ($the_query -> have_posts()) : $the_query -> the_post();
//Loop content
endwhile;
endif;
wp_reset_postdata();
die($out);
}
Jquery Function
var count = 0;
function load_more_team(count) {
var count = count + 12
var button = $('#more_posts'),
data = {
'action': 'ajax_more_team',
'offset': count
}
$.ajax({
url: team_ajax.ajaxurl,
data: data,
type: 'POST',
dataType: 'html',
success: function(data){
if(data.length){
$("#ajax_posts").append(data);
button.attr("disabled",false);
} else{
button.attr("disabled",true);
}
}
});
return false;
}
$('#more_posts').click(function() {
$("#more_posts").attr("disabled",true); // Disable the button, temp.
load_more_team();
});
Edit:
To add a bit of extra context, I am adding the initial page template loop.
page.php
<div id="ajax_posts" class="row">
<?php
$args = array(
'post_type' => 'team',
'posts_per_page' => 12
);
$the_query = new WP_Query($args);
?>
<?php if($the_query->have_posts()) : while($the_query->have_posts()) : $the_query->the_post(); ?>
<?php $id = get_the_id(); ?>
<div class="col-6 col-md-4 col-lg-3 col-xl-2 mb-4">
<div class="team-member">
<a href="#" data-toggle="modal" data-target="#<?php echo $id ?>">
<img class="img-fluid" src="<?php the_field('employee_headshot'); ?>" alt="<?php the_field('employee_name'); ?>">
</a>
<div class="team-info">
<h6><?php the_field('employee_name'); ?></h6>
</div>
<a href="" data-toggle="modal" data-target="#myModal">
<div class="modal-icon">
<img class="img-fluid" src="<?php bloginfo('template_directory');?>/imgs/modal-icon.svg">
</div>
</a>
</div>
<!-- Modal -->
<div class="modal fade" id="<?php echo $id ?>" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="team-close-btn">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<img class="img-fluid" src="<?php the_field('employee_headshot'); ?>" alt="Alice George">
<div class="team-info">
<h6><?php the_field('employee_name'); ?></h6>
<p><strong>Title:<br></strong> <?php the_field('employee_title'); ?></p>
<p><strong>Company:<br></strong> <?php the_field('employee_company'); ?></p>
</div>
</div>
</div>
</div>
</div>
</div>
<?php endwhile; endif; ?>
</div>
<?php
if( $the_query->max_num_pages > 1)
echo '<div id="more_posts" class="btn-primary mt-4">View More</div>'
?>
<?php wp_reset_postdata(); ?>
</div>
Updated to your code, this should work for you. I think count was a bit confusing, cause for me, it wasn't immediatly clear if it was a total amount or the current page.
Not sure how you're recieving the $offset value in your PHP function but $offset here should be just the POST value 'offset', no + 12 or anything. That way at first call you have a offset of 0 and get first 12 records starting at row 1, next time you have offset of 12 and get next 12 records (starting at the 13th row). Your post_per_page remain 12, while offset multiplies. Offset indicates from what records it should begin taking the "post_per_page" amount.
function ajax_more_team($offset) {
$offset = $_POST['offset'];
header("Content-Type: text/html");
$args = array(
'suppress_filters' => true,
'post_type' => 'team',
'posts_per_page' => 12,
'offset' => $offset,
);
$the_query = new WP_Query($args);
if ($the_query -> have_posts()) : while ($the_query -> have_posts()) : $the_query -> the_post();
//Loop content
endwhile;
endif;
wp_reset_postdata();
die($out);
}
-
var page = 1; // first page
function load_more_team() {
var button = $('#more_posts'),
data = {
'action': 'ajax_more_team',
'offset': page * 12 // first time 0 * 12 = offset 0
}
$.ajax({
url: team_ajax.ajaxurl,
data: data,
type: 'POST',
dataType: 'html',
success: function(data){
if(data.length){
$("#ajax_posts").append(data);
button.attr("disabled",false);
} else{
button.attr("disabled",true);
}
page++; // increment page after first request
}
});
return false;
}
var page = 2; // first page already loaded
function load_more_team() {
var button = $('#more_posts'),
data = {
'action': 'ajax_more_team',
'paged': page
}
$.ajax({
url: team_ajax.ajaxurl,
data: data,
type: 'POST',
dataType: 'html',
success: function(data){
if(data.length){
$("#ajax_posts").append(data);
button.attr("disabled",false);
} else{
button.attr("disabled",true);
}
page++; // increment page after request
}
});
return false;
}
function ajax_more_team() {
$paged = $_POST['paged'];
header("Content-Type: text/html");
$args = array(
'suppress_filters' => true,
'post_type' => 'team',
'post_status' => 'publish',
'posts_per_page' => 12,
'paged' => $paged,
);
$the_query = new WP_Query($args);
if ($the_query -> have_posts()) : while ($the_query -> have_posts()) : $the_query -> the_post();
//Loop content
endwhile;
endif;
wp_reset_postdata();
die($out);
}
Related
using ACF PRO to created a field with a gallery, which should be displayed with other dynamic content in the modal when clicking on the post, the text content is displayed but the gallery not show, or show from the first post in cycle
The code that displays the loop on the page
//post query
$query = new WP_Query( $query_args );
ob_start();
// Wrap with a div when infinity load
echo ( $pagination_type == 'load_more' ) ? '<div class="postgrid-wrapper">' : '';
// Start posts query
if( $query->have_posts() ): ?>
<div class="<?php echo esc_attr( "post_grid col-3 layout_{$args['layout']} {$args['animation']} " ); ?>">
<?php while( $query->have_posts()): $query->the_post(); ?>
<?php if($args['layout'] == "1"){ ?>
<div class="grid_col" >
<div data-id="<?php the_ID(); ?>" class="single_grid view-post"><div class="more-button"><p>show more</p></div>
<div class="thumb">
<?php the_post_thumbnail('full'); ?>
</div>
<div class="cont">
<h2 class="title"><?php echo get_the_title(); ?></h2></a>
<div class="subtitle"><?php the_field('subtitle'); ?></div>
</div>
</div>
</div>
<?php } else if( $args['layout'] == 2 ){ ?>
<?php } ?>
<?php endwhile; ?>
</div>
Modal using ajax to show dynamic content (functions.php)
function load_post_by_ajax_callback() {
check_ajax_referer('view_post', 'security');
$args = array(
'post_type' => 'post',
'p' => $_POST['id'],
);
$portfolios = new WP_Query( $args );
$arr_response = array();
if ($myposts->have_posts()) {
while($myposts->have_posts()) {
$myposts->the_post();
//
$arr_response = array(
'title' => get_field('acf-field-title'),
'subtitle' => get_field('acf-field-subtitle'),
'content' => get_field('acf-field-content'),
'autor' => get_field('acf-field-autor'),
'thumb' => get_the_post_thumbnail(),
'slider' => get_field('gallery'),
);
}
wp_reset_postdata();
}
echo json_encode($arr_response);
wp_die();
}
add_action('wp_ajax_load_post_by_ajax', 'load_post_by_ajax_callback');
add_action('wp_ajax_nopriv_load_post_by_ajax', 'load_post_by_ajax_callback');
Script parsing content from the post and show content in modal with the assigned id from acf field
jQuery(function($) {
$('body').on('click', '.view-post', function() {
var data = {
'action': 'load_post_by_ajax',
'id': $(this).data('id'),
'security': blog.security
};
$.post(blog.ajaxurl, data, function(response) {
response = JSON.parse(response);
$('#postModal .modal-body #postModalTilte').text(response.title);
$('#postModal .modal-body #postModalSubtitle').html(response.subtitle);
$('#postModal .modal-body #postModalContent').html(response.content);
$('#postModal .modal-body #postModalAutor').html(response.autor);
$('#postModal .modal-body #postModalSlider').html(response.slider);
var postModal = new bootstrap.Modal(document.getElementById('postModal'));
postModal.show();
});
});
Bootstrap modal code
<div class="modal" id="postModal">
<div class="modal-dialog modal-dialog-centered" style="max-width:70%">
<div class="modal-content">
<div class="modal-body">
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close" style="float:right;border:none;"></button>
<div class="row">
<div class="col-left">
<div class="grid-gallery" id="postModalSlider"></div>
</div>
<div class="col-right">
<h5 class="portfolio-title" id="postModalTitle">Title: </h5>
<p class="portfolio-customer" id="postModalSubtitle">Subtitle: </p>
<p class="portfolio-review" id="postModalContent">Content</p>
<p class="portfolio-price" id="postModalAutor">Autor: </p>
</div>
</div>
</div>
</div>
</div>
</div>
I tried to paste in modal, the example gallery from the ACF documentation, in this case they are shown only from the very first post and the necessary not show.
I understand that the script cannot parse the necessary gallery data from the post, but I don't know how to fix it
I used a plugin called "Insert PHP Code Snippet" to create this page:
URL; https://sololoaded.com/All-Profiles/
Snippet Short Code; [xyz-ips snippet="All-Profiles"]
I later find out that most of my pages are appearing inside the page
for a exmaple:
DMCA PAGE
About Us page
please help I need a code on how to remove these pages from appearing inside the snippet page:
Here is the code:
<!-- query -->
<!-- query -->
<?php
add_action('admin_init', function () {
// Redirect any user trying to access comments page
global $pagenow;
if ($pagenow === 'edit-comments.php') {
wp_redirect(admin_url());
exit;
}
// Remove comments metabox from dashboard
remove_meta_box('dashboard_recent_comments', 'dashboard', 'normal');
// Disable support for comments and trackbacks in post types
foreach (get_post_types() as $post_type) {
if (post_type_supports($post_type, 'comments')) {
remove_post_type_support($post_type, 'comments');
remove_post_type_support($post_type, 'trackbacks');
}
}
});
// Close comments on the front-end
add_filter('comments_open', '__return_false', 20, 2);
add_filter('pings_open', '__return_false', 20, 2);
// Hide existing comments
add_filter('comments_array', '__return_empty_array', 10, 2);
// Remove comments page in menu
add_action('admin_menu', function () {
remove_menu_page('edit-comments.php');
});
// Remove comments links from admin bar
add_action('init', function () {
if (is_admin_bar_showing()) {
remove_action('admin_bar_menu', 'wp_admin_bar_comments_menu', 60);
}
});
global $post;
$post_slug=$post->post_name;
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$query = new WP_Query( array(
'post_type' => array( 'page' ),
'post__not_in' => array(3,5550,8, 73, 6, 11, 9817,22177),
'posts_per_page' => 19,
'orderby' => 'title',
'order' => 'ASC',
'paged' => $paged
) );
?>
<?php if ( $query->have_posts() ) : ?>
<section class="top-stories section-theme-border">
<!-- begin loop -->
<div style="background:white; padding:15px; border-radius: 5px;">
<div class="row row-lg">
<?php while ( $query->have_posts() ) : $query->the_post();
$url1 = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail' );
$url2 = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium');
$image_id = get_post_thumbnail_id();
$img_src = wp_get_attachment_image_url( $image_id, 'large' );
$img_srcset = wp_get_attachment_image_srcset( $image_id, 'full' );
$img_alt = get_post_meta( $image_id, '_wp_attachment_image_alt', true );
?>
<div class="col-xs-4 col-sm-4 col-md-3">
<div class="item">
<div class="item-media rounded ">
<a href="<?php the_permalink(); ?>"
class="item-media-content"
style="background-image: url('<?php echo esc_attr( $img_src ); ?>');"></a>
</div>
<div class="item-info text-center">
<div class="post-title a item-title text-ellipsis">
<?php the_title(); ?>
</div>
</div>
</div>
</div>
<?php endwhile; ?>
</div></div>
<!-- end loop -->
<div class="container-wrapper songs-pag">
<?php
echo paginate_links( array(
'base' => str_replace( 999999999, '%#%', esc_url( get_pagenum_link( 999999999 ) ) ),
'total' => $query->max_num_pages,
'current' => max( 1, get_query_var( 'paged' ) ),
'format' => '?paged=%#%',
'show_all' => false,
'type' => 'plain',
'end_size' => 2,
'mid_size' => 1,
'prev_next' => true,
'prev_text' => sprintf( '<i></i> %1$s', __( 'Previous', 'text-domain' ) ),
'next_text' => sprintf( '%1$s <i></i>', __( 'Next', 'text-domain' ) ),
'add_args' => false,
'add_fragment' => '',
) );
?>
</div>
</section>
<?php wp_reset_postdata(); ?>
<?php else : ?>
<?php endif; ?>
As I observe you have problem in below loop and specifically in funcions the_permalink() and the_title() that is why you are getting all other details as well, so check first than you get it.
<?php while ( $query->have_posts() ) : $query->the_post();
$url1 = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail' );
$url2 = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium');
$image_id = get_post_thumbnail_id();
$img_src = wp_get_attachment_image_url( $image_id, 'large' );
$img_srcset = wp_get_attachment_image_srcset( $image_id, 'full' );
$img_alt = get_post_meta( $image_id, '_wp_attachment_image_alt', true );
?>
<div class="col-xs-4 col-sm-4 col-md-3">
<div class="item">
<div class="item-media rounded ">
<a href="<?php the_permalink(); ?>"
class="item-media-content"
style="background-image: url('<?php echo esc_attr( $img_src ); ?>');"></a>
</div>
<div class="item-info text-center">
<div class="post-title a item-title text-ellipsis">
<?php the_title(); ?>
</div>
</div>
</div>
</div>
<?php endwhile; ?>
</div></div>
<!-- end loop -->
I'm trying to use slick slider as the Previous and Next buttons on a WordPress single CPT page.
So the slider would call all the posts of a specific CPT and show the featured image of the current post and on either side it would show the featured image of the previous and next posts.
As you navigate through the slide the corresponding content would appear.
The problem is that as you slide through you'll get the correct images and content, but the URL stays the same. Also you can't link to a specific post because it'll just go to the beginning of the slide.
Right now, this is what my single-CPT.php looks like
<?php
get_header();
rewind_posts();
if (have_posts()) {
while ( have_posts() ) : the_post();
$post_id = get_the_ID();
?>
// BEGIN SLIDER (WHERE FEATURED IMAGES ARE THE SLIDES)//
<section class="slider center">
<?php
$index = 0;
$carousel_args = array(
'post_type' => 'CPT',
'posts_per_page' => -1,
);
$carousel_query = new WP_Query( $carousel_args );
if ( $carousel_query->have_posts() ) {
while ( $carousel_query->have_posts() ) {
$carousel_query->the_post();
$title = get_the_title();
$link = get_permalink();
if ( has_post_thumbnail() ) {
$post_thumbnail_id = get_post_thumbnail_id();
$post_thumbnail_image = wp_get_attachment_image_src( $post_thumbnail_id, 'large' );
$post_thumb = $post_thumbnail_image[0];
} else {
$post_thumb = '';
}
$content = get_the_content();
$excerpt = get_the_excerpt();
// output//
?>
<div class="wow slide-in slide">
<div class="active">
<a href="<?php echo $link; ?>">
<img src="<?php echo $post_thumb; ?>" />
</a>
</div>
</div>
<?php $index++;
}
}
wp_reset_postdata();
endwhile;
?>
</section>
//END SLIDER - BEGIN CONTENT//
<div id="archive-post">
<div class="row">
<div class="columns small-12 medium-10 medium-offset-1 large-offset-0 large-8">
<article id="post-<?php the_ID(); ?>" role="article">
<div class="post-title">
<div class="row">
<div class="columns">
<h3><?php the_title(); ?></h3>
</div>
</div>
</div>
<div class="post-content">
<div class="row">
<div class="columns">
<?php the_content(); ?>
</div>
</div>
</div>
</article>
</div>
</div>
</div>
Basically I need the URL to update along with the slide without refreshing the page. Is there any way to accomplish this?
Okay, so with a ton of help from a friend, I found a way to do this with the magic of AJAX and HTML5 Apis
Basically what you have to do is use the HTML5 Api to manipulate the browser's history, and use AJAX to load the desired content without refreshing. Here's what it ended up looking like:
The single post template stayed pretty much the same except I changed the slide query output a little from
<a href="<?php echo $link; ?>">
to
<a href="<?php echo $link; ?>" class="js-switchSlide" data-ajaxurl="<?php echo admin_url('admin-ajax.php'); ?>" data-title="<?php echo get_the_title(); ?>" data-id="<?php echo get_the_ID(); ?>">
I added the js-switchSlide class to be able to call it in my JS and AJAX functions later.
I added a couple of data attributes (data-ajaxurl,data-title, and data-id) that I will use in the ajax function.
The content section has been changed too, notice the new classes and id's
<div id="archive-post">
<div class="row">
<div class="columns small-12 medium-10 medium-offset-1 large-offset-0 large-8">
<article id="post-<?php the_ID(); ?>" <?php post_class( array('post-page', 'js-slideContainer') ); ?> role="article">
<input type="hidden" id="currentSlide" value="<?php the_ID(); ?>">
<div class="post-title">
<div class="row">
<div class="columns">
<h3 class="js-slideTitle"><?php the_title(); ?></h3>
</div>
</div>
</div>
<div class="post-content">
<div class="row">
<div class="columns js-slideContent">
<?php the_content(); ?>
</div>
</div>
</div>
</article>
</div>
</div>
</div>
Here is the JS:
$(document).ready(function() {
This is used later to see whether the actual slide or the button was clicked
`var clickedSlide = true;`
Initiate the slide
$navslider = $('.slider').slick({
centerMode: true,
infinite: true,
slidesToShow: 3,
slidesToScroll: 1,
arrows: true,
focusOnSelect: true,
Here I make the slide responsive
`responsive: [
{
breakpoint: 1068,
settings: {
initialSlide: 0,
infinite: true,
slidesToShow: 3,
slidesToScroll: 1,
}
},
{
breakpoint: 768,
settings: {
initialSlide: 0,
infinite: true,
slidesToShow: 3,
slidesToScroll: 1,
}
},
{
breakpoint: 480,
settings: {
initialSlide: 0,
infinite: true,
slidesToShow: 3,
slidesToScroll: 1,
}
},]
});`
Here is my Ajax call
`function slidesAjaxCall(slideID, slideTitle, slideHref, ajaxurl) {`
This part just makes the loading of the content a little smoother by fading it in and out.
`$( '.js-slideContainer' ).animate({
opacity: 0
}, 320);`
This is where I manipulate the browser history
`history.pushState(null, slideTitle, slideHref);
document.title = slideTitle;`
Here is where I place the values from the data attributes using POST method. Type is just the custom post type and action is the name of the Ajax function.
$.ajax({
url : ajaxurl,
method: 'POST',
data: {
id: slideID,
type : 'CPT',
action: 'hc_load_slide'
},
Self explanatory
`error : function( response ){
console.log('error');
},`
If successful:
`success : function( response ){
if( response === 0 ){
console.log('no slide found');
$( '.js-slideContainer' ).animate({
opacity: 1
}, 320);
} else {`
The post data is collected in the Ajax function in JSON format so it has to be parsed and inserted into the html
`var data = JSON.parse(response);
$( '.js-slideTitle' ).text(data.title);
$( '.js-slideContent' ).html(data.content);`
Make it behave nicely
`setTimeout(function(){
$( '.js-slideContainer' ).animate({
opacity: 1
}, 320);
}, 100);
}
}
});
}`
.js-switchSlide is the class in the a tag so I prevent it from going refreshing the page when clicked.
`$('.js-switcSlide').click(function(e){
e.preventDefault();`
This says that the slide was clicked, this will keep it from calling the ajax function twice
`clickedSlide = true;`
Collect all the values from the data attributes:
`var babyID = e.currentTarget.dataset.id;
var babyTitle = e.currentTarget.dataset.title;
var babyHref = e.currentTarget.href;
var ajaxurl = e.currentTarget.dataset.ajaxurl;`
Call the function
`babiesAjaxCall(babyID, babyTitle, babyHref, ajaxurl);
});`
Okay this next part loads the appropriate slide and content using the permalink. Remember, one of the issues was that I could get the slide to work fine, but when I navigated to a specific post the slide would start from the beginning.
`var currentSlideID = $( '#currentSlide' ).val();
var $slide = $(".slider [data-id='" + currentSlide + "']");
var slideIndex = $slide.parents('.slide').data("slick-index");
$babyslider.slick("goTo", slideIndex);
/* Trigger Ajax call if Chevron is clicked and not Slide */
$slider.on('afterChange', function(event, slick, currentSlide, nextSlide){
// Stop if clieckedSlide === true;
if (clickedSlide) {
clickedSlide = false;
return;
}
var slideIndex = $('[data-slick-index="' + currentSlide + '"]').find('.js-switchSlide');
var slideID = slideIndex.data('id');
var slideTitle = slideIndex.data('title');
var slideHref = slideIndex.attr('href');
var ajaxurl = slideIndex.data('ajaxurl');
babiesAjaxCall(babyID, babyTitle, babyHref, ajaxurl);
});
});`
Meanwhile, the Ajax function looks like this
`add_action( 'wp_ajax_nopriv_hc_load_slide', 'hc_load_slide' );
add_action( 'wp_ajax_hc_load_slide', 'hc_load_slide' );
function hc_load_baby() {
$id = $_POST["id"];
$type = $_POST["type"];
// echo $id . ' - ' . $type;
$args = array(
'post_type' => $type,
'p' => $id,
);
$slide = new WP_Query( $args );
if ( $slide->have_posts() ) :
while ( $slide ->have_posts() ) : $slide->the_post();
$title = get_the_title();
$content = apply_filters('the_content', get_the_content() );
endwhile;
endif;
echo json_encode([ 'title' => $title, 'content' => $content ]);
die();
}`
I know it's a long answer, but I hope that makes sense. It accomplishes exactly what I wanted. Thanks alecaddd for the lessons.
http://sols.no/galleri/
If you scroll down to the bottom of the page you could see the new images loading but I want it to load them before scrolling all the way down to the bottom.
Here's the code from the page template
<?php
/**
* Template Name: gallery
*/
get_header();
?>
<main id="main" role="main">
<div class="page gallery">
<?php
/*$args = array('posts_per_page' => -1,'post_type' => 'post','orderby' => 'date', 'order' => 'DESC');
$posts_array = get_posts( $args );
$postids=array();
foreach($posts_array as $post){
$postids[]=$post->ID;
}*/
//query_posts(array('post_type'=>'attachment','posts_per_page' => 15,'paged'=>1,'post_status' => 'any', 'post_parent' => null));
$args = array( 'post_type' => 'attachment','post_status'=>'inherit', 'posts_per_page' => 25,'paged'=>1 , 'post_parent' => null, 'orderby' => 'date', 'order' => 'DESC' );
$attach = new wp_Query( $args );
//while ( have_posts() ) : the_post();
if ( $attach->have_posts()) {
while ( $attach->have_posts() ) {
$attach->the_post();
$parent=wp_get_post_parent_id(get_the_ID());
?>
<article class="post-<?php the_ID();?> gallery type-gallery status-publish has-post-thumbnail hentry" id="post-<?php the_ID();?>" >
<div class="entry-thumbnail">
<a href="<?php echo get_permalink($parent); ?>" rel="bookmark">
<?php //the_post_thumbnail('gallery-thumb'); ?>
<?php echo wp_get_attachment_image( get_the_ID(), 'gallery-thumb' ); ?>
</a>
</div><!-- .entry-thumbnail -->
<header class="entry-header">
<div class="entry-meta">
<?php twentytwelve_entry_meta(); ?>
</div>
<h1 class="entry-title">
<?php echo get_the_title($parent); ?>
</h1>
</header><!-- entry-header -->
<span class="screen-reader-text">Continue reading <span class="meta-nav">→</span></span>
</article>
<?php
}
//endwhile;
wp_reset_query();
}
// Reset Query
//load more links
?>
</div>
<div class="gallery-btn" style="display:none;">
<img src="<?php echo get_template_directory_uri(); ?>/images/ajax-loader.gif" class="loader-img" />
<a class="loadmore" href="#" rel="2">Load more</a>
</div>
</main>
<script>
jQuery(document).ready(function($){
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
$("a.loadmore").click();
}
});
});
jQuery(document).ready(function($){
$("a.loadmore").click(function(){
var pageno=parseInt($(this).attr('rel'));
$(".gallery-btn").addClass('loader');
// here we call ajax
var data = {
action: 'loadmore',
pageno: pageno,
_ajax_nonce: '<?php echo wp_create_nonce( 'my_ajax_nonce' ); ?>'
};
$.post(MyAjax.ajaxurl, data, function(response) {
if(response!=""){
$(".page.gallery").append(response);
$("a.loadmore").attr('rel',pageno+1);
$(".gallery-btn").removeClass('loader');
}
else{
$("a.loadmore").hide();
$(".gallery-btn").removeClass('loader');
}
});
//
return false;
});
});
</script>
<?php get_footer(); ?>
I figured out it has to do with this code. But I am unable to figure out how to make it work.
jQuery(document).ready(function($){
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
$("a.loadmore").click();
}
});
});
please use this new one...
jQuery(document).ready(function($){
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()-800)
{
$("a.loadmore").click();
}
});
});
You can try this. it might be helpful to you.
jQuery(document).ready(function($){
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()-400) {
$("a.loadmore").click();
}
});
});
I received some help previously in order to build a Wordpress Ajax Load more function, However the site I am building is using different variances of this on different pages pages.
The issue I'm having is controlling the variables such as 'post-type' 'postsPerPage' from the template file, the person that helped me gave me a method of creating a variable for 'category' and passing it between the template, functions.php and JS file which works perfectly, all I want to do is replicate that for 'postsPerPage' and 'post-type', easy right?
Apparently not,
I thought I had it right, however the functions.php seems like it doesnt recieve the 'postsPerPage' variable at all:
I'll put the original code for the initial instance of this that works followed by each the changes I've made to try make it work:
Initial Template File
<!-- ************************************************************************** -->
<!-- This controls the Load More AJax Function and Loadout for dropdow sections -->
<!-- ************************************************************************** -->
<div id="ajax-posts" class="row">
<?php
$cat_id = 2;
$postsPerPage = 4;
$args = array(
'post_type' => 'post',
'posts_per_page' => $postsPerPage,
'cat' => $cat_id
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<div class="small-6 large-3 columns end thumb">
<div class="grid">
<figure class="effect-zoe">
<?php the_post_thumbnail( $size, $attr ); ?>
<a href="<?php the_permalink(); ?> "><figcaption>
<h2><?php the_title(); ?></h2>
<hr class="light">
<p class="description"><?php the_content(); ?></p>
</figcaption></a>
</figure>
</div>
</div>
<?php
endwhile;
wp_reset_postdata();
?>
</div>
<a id="more_posts" data-category="<?php echo $cat_id; ?>">Load More</a>
<!-- **************************************************************** -->
<!-- End of Load More AJax Function and Loadout for dropdown sections -->
<!-- **************************************************************** -->
Edited Template File
<!-- ************************************************************************** -->
<!-- This controls the Load More AJax Function and Loadout for dropdow sections -->
<!-- ************************************************************************** -->
<div id="ajax-posts" class="row">
<?php
$ppp_id = 6;
$cat_id = 2;
$postit_id = 'post';
$postsPerPage = 6;
$args = array(
'post_type' => $postit_id,
'posts_per_page' => $postsPerPage,
'cat' => $cat_id
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<div class="small-6 large-3 columns end thumb">
<div class="grid">
<figure class="effect-zoe">
<?php the_post_thumbnail( $size, $attr ); ?>
<a href="<?php the_permalink(); ?> "><figcaption>
<h2><?php the_title(); ?></h2>
<hr class="light">
<p class="description"><?php the_content(); ?></p>
</figcaption></a>
</figure>
</div>
</div>
<?php
endwhile;
wp_reset_postdata();
?>
</div>
<a id="more_posts"
data-category="<?php echo $cat_id; ?>"
data-ppp="<?php echo $postsPerPage; ?>"
>Load More</a>
<!-- **************************************************************** -->
<!-- End of Load More AJax Function and Loadout for dropdown sections -->
<!-- **************************************************************** -->
Initial functions.php
function more_product_ajax(){
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 4;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
$cat = (isset($_POST['cat_id'])) ? $_POST['cat_id'] : '';
header("Content-Type: text/html");
$args = array(
'post_type' => 'post',
'posts_per_page' => $ppp,
'cat' => $cat,
'paged' => $page,
);
$loop = new WP_Query($args);
$out = '';
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
$out .= '<div class="small-6 large-3 columns end thumb">
<div class="grid">
<figure class="effect-zoe light">
<?php the_post_thumbnail( $size, $attr ); ?>
</figure>
<h2 class="product-load"><?php the_title() ?></h2>
</div>
</div>';
endwhile;
endif;
wp_reset_postdata();
die($out);
}
add_action('wp_ajax_nopriv_more_product_ajax', 'more_product_ajax');
add_action('wp_ajax_more_product_ajax', 'more_product_ajax');
Edited functions.php
/***********************************************
This controls initial load more function
***********************************************/
function more_post_ajax(){
$ppp = (isset($_POST['postsPerPage'])) ? $_POST['postsPerPage'] : '';
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
$cat = (isset($_POST['cat_id'])) ? $_POST['cat_id'] : '';
header("Content-Type: text/html");
$args = array(
'post_type' => 'post',
'posts_per_page' => $ppp,
'cat' => $cat,
'paged' => $page,
);
$loop = new WP_Query($args);
$out = '';
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
$out .= '<div class="small-6 large-3 columns end thumb">
<div class="grid">
<figure class="effect-zoe">
'.get_the_post_thumbnail( get_the_ID(), $size, $attr ).'
<figcaption>
<h2>'.get_the_title().'</h2>
<hr class="light">
<p class="description">'.get_the_content().'</p>
</figcaption>
</figure>
</div>
</div>';
endwhile;
endif;
wp_reset_postdata();
die($out);
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
Initial Custom.js
var ppp = 4; // Post per page
var cat = $('#more_posts').data('category');
var pageNumber = 1;
function load_posts(){
pageNumber++;
var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp' + ppp + '&action=more_post_ajax';
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function(data){
var $data = $(data);
if($data.length){
$("#ajax-posts").append($data);
$("#more_posts").attr("disabled",false);
} else{
$("#more_posts").attr("disabled",true);
}
},
error : function(jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
$("#more_posts").on("click",function(){ // When btn is pressed.
$("#more_posts").attr("disabled",true); // Disable the button, temp.
load_posts();
});
Edited custom.js
var ppp = $('#more_posts').data('ppp');
var cat = $('#more_posts').data('category');
var pageNumber = 1;
function load_posts(){
pageNumber++;
var str = '&cat=' + cat + '&pageNumber=' + pageNumber + '&ppp' + ppp + '&action=more_post_ajax';
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function(data){
var $data = $(data);
if($data.length){
$("#ajax-posts").append($data);
$("#more_posts").attr("disabled",false);
} else{
$("#more_posts").attr("disabled",true);
}
},
error : function(jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
$("#more_posts").on("click",function(){ // When btn is pressed.
$("#more_posts").attr("disabled",true); // Disable the button, temp.
load_posts();
});
Sorry about all the code, just want to give you all the full picture, can anyone see where I am going wrong?