So essentially I'm able to get WP and AJAX to load a page whenever I've got a 'click' event in JQuery. With the click event it works properly, however, when switching it all to function on scroll, instead of properly reloading the following post or posts (as it does when you click) it instead reloads the entire page of the site within the designated div.
Here's my code:
Ajax.php
add_action('wp_ajax_nopriv_art_load_single','art_load_single');
add_action('wp_ajax_art_load_single','art_load_single');
function art_load_single(){
$paged = $_POST["page"]+1;
$query = new WP_Query(array(
'post_type' => 'post',
'post_status' => 'publish',
'paged' => $paged,
'posts_per_page' => 1
));
?>
<?php if($query->have_posts()):
while($query->have_posts()): $query->the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<div class="entry-title">
<?php the_title( '<h1>', '</h1>' ); ?>
<h2 class="sub-headline">
<?php if ( ! has_excerpt() ) {
echo '';
} else {
the_excerpt();
} ?>
</h2>
</div>
<?php if ( has_post_thumbnail()) : ?>
<div class="article-featured-image">
<?php the_post_thumbnail('large'); ?>
</div>
<?php endif; ?>
</header><!-- .entry-header -->
<div class="entry-content">
<?php the_content(); ?>
<?php
wp_link_pages( array(
'before' => '<div class="page-links">' . __( 'Pages:', 'some_theme' ),
'after' => '</div>',
) );
?>
</div><!-- .entry-content -->
</article><!-- #post-## -->
<?php endwhile;
endif;
wp_reset_postdata(); ?>
<?php die();
}
Load-more.js
var postContainer = document.getElementById('primary');
var request_in_progress = false;
$(window).scroll(function(){
infiniteScroll();
});
function infiniteScroll(){
var content_height = postContainer.offsetHeight;
var current_y = window.innerHeight + window.pageYOffset;
if(current_y >= content_height)
showSinglePost();
}
}
//$(document).on('click','.load-single-article', function(){
function showSinglePost(){
if(request_in_progress) { return; }
request_in_progress = true;
var that = $(this);
var page = that.data('page');
var newPage = page+1;
var ajaxurl = that.data('url');
that.find('.text').html('LOADING...');
$.ajax({
url : ajaxurl,
type : 'post',
data : {
page : page,
action : 'art_load_single',
dataType: 'post'
},
error : function( response ){
console.log(response);
},
success : function( response ) {
setTimeout(function(){
that.data('page', newPage);
$('#primary').append( response );
that.find('.text').html('VIEW MORE');
request_in_progress = false;
}, 500);
}
});
}
Leaving in the 'click' event just in case. Finally my button for clicking is below:
<a class="view-btn load-single-article" data-page="1" data-url="<?php echo admin_url('admin-ajax.php'); ?>"><span class="text">VIEW MORE</span></a>
Being slightly new to AJAX I believe it could just be the URL reacts differently when called on click vs when loading on scroll, or maybe the click is just working as a fluke. Any help is appreciated!
This is a stripped back version of what you want, so you should be able to just plug in your own article loading etc.. It starts off with a bunch of articles already loaded and when you scroll it checks to see where one the page you are. If you're at the bottom of the page then it loads a new article and appends it.
var articleCount = 0;
var $window = $(window);
var $body = $("body");
$window.on("scroll", function() {
// check to see if we're near the bottom of the page
if ($window.scrollTop() > $body.height() - $window.innerHeight()) {
// we are at the bottom, so load a new article
loadNextArticle();
}
});
// make this function actually load an article and append it to the page
function loadNextArticle() {
articleCount++;
$body.append("<div class=\"single-article\">I am article number " + articleCount + "</div>");
}
// create some articles when the page loads...
for (var i = 0; i < 6; i++) {
loadNextArticle();
}
.single-article {
background-color: rgb(230, 230, 240);
border: 1px solid rgba(0, 0, 0, 0.1);
border-radius: 10px;
height: 200px;
margin: 10px;
padding: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Obviously you'll need to amend this to suit your specific requirements, but I've tried to make it as generic as possible. Realistically you should just be able to copy/paste the Javascript into your site and swap out the part that loads and appends a new article.
Related
I have custom post types with JS filtering (based on category). There are simple html boxes + php code with ACF fields what display after select category.
Problem is it take 1 second or more to load all this html boxes so its not so smooth.
This is my JS (file filters.js):
(function($){
$(document).ready(function(){
$(document).on('click', '.js-filter-item > a', function(e){
e.preventDefault();
var category = $(this).data('category');
$.ajax({
url:wp_ajax.ajax_url,
data: { action: 'filter', category: category },
type: 'post',
success: function(result) {
$('.js-filter').html(result);
},
error: function(result) {
console.warn(result);
}
});
});
});
})(jQuery);
This is html of box what is loaded (file content_pozice_box.php)
<a href="<?php echo get_permalink();?>"><div class="vypis_pozice">
<div class="projekt-wrapper">
<?php
$projekt = get_field('projekt');
if( get_field('projekt') == 'XXX' ) {
?>
<div class="logo-wrapper">
<img src="https://YYY.png" class="logo-wrapper-img">
</div><?php
}
if( get_field('projekt') == 'YYY' ) {
?>
<div class="logo-wrapper">
<img src="https://XXX.png" class="logo-wrapper-img">
</div>
<?php
}
?>
<div class="field_projekt"><h3><?php the_field('projekt');?></h3><div class="field_AAA">AAA:
<?php if ( get_field( 'AAA' ) ): ?>
<?php the_field('AAA');?>
<?php else: // field_name returned false ?>
dohodou
<?php endif; // end of if field_name logic ?>
</div></div>
</div>
<?php the_title('<h3>', '</h3>'); ?>
<div class="location-wrapper">
<div class="BBB"><img src="https://BBB.png"><?php the_field('BBB');?></div>
<div class="CCC"><img src="https://CCC.png"><?php the_field('CCC');?></div>
</div>
<div class="DDD"><?php $cat = get_the_category(); echo $cat[0]->cat_name; ?></div><div class="job-button">Otevřít</div>
</div></a>
PHP (loading JS, Ajax, function)
function load_scripts() {
wp_enqueue_script('ajax', get_stylesheet_directory_uri() . '/' . 'template-parts/' .'filters.js', array('jquery'), NULL, true);
wp_localize_script('ajax' , 'wp_ajax',
array('ajax_url' => admin_url('admin-ajax.php'))
);
}
add_action( 'wp_enqueue_scripts', 'load_scripts');
add_action( 'wp_ajax_nopriv_filter', 'filter_ajax' );
add_action( 'wp_ajax_filter', 'filter_ajax' );
function filter_ajax() {
$category = $_POST['category'];
$args = array(
'post_type' => 'pozice',
'posts_per_page' => -1
);
if(isset($category)) {
$args['category__in'] = array($category);
}
$query = new WP_Query($args);
if($query->have_posts()) :
while($query->have_posts()) : $query->the_post();
include("content_pozice_box.php");
endwhile;
endif;
wp_reset_postdata();
die();
}
This won't solve all your problems but the first thing you should do is reduce your database calls. get_field('projekt') is called 4 times, which runs for every iteration of your loop. Oddly, you've already set it to a variable:
$projekt = get_field('projekt');
But you're not using the variable anywhere. So try replacing that first, so that it only runs once per iteration:
if ( $projekt ) {...}
While you're at it you should always escape output for security's sake. I.E. Instead of <h3><?php the_field('projekt');?></h3> replace with <h3><?php echo esc_html( $projekt ); ?></h3>.
To find other sources of inefficiencies you might try the Query Monitor plugin, as well as your browser's dev tools. I'm not sure about your JS. It looks fine to me but perhaps someone else here will notice something.
I cant get this to work. I am trying to create a custom post type grid with ajax load more button to show 6 mosts per page in the grid. I can get the posts to show but the Load More button just scrolls to the top of the page like a normal anchor link.
My theme code:
<div class="tabgrid">
<?php
$postsPerPage = 6;
$args = array(
'post_type' => 'dslc_projects',
'posts_per_page' => $postsPerPage,
'offset' => $offset
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?><div class="project-grid-item">
<a href="<?php the_permalink() ?>">
<h3><?php the_title() ?></h3>
<p>View project...</p> </a>
</div><?php
endwhile; ?>
<?php echo '<div id="more_posts">Load More</div>';
wp_reset_postdata();
?>
</div>
</div>
My PHP:
function more_post_ajax(){
$offset = $_POST["offset"];
$ppp = $_POST["ppp"];
header("Content-Type: text/html");
$args = array(
'post_type' => 'post',
'posts_per_page' => $ppp,
'offset' => $offset
);
$loop = new WP_Query($args);
while ($loop->have_posts()) { $loop->the_post();
the_content();
}
exit;
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
My JS:
var ajaxUrl = "<?php echo admin_url('admin-ajax.php')?>";
var page = 1; // What page we are on.
var ppp = 6; // Post per page
$("#more_posts").on("click",function(){ // When btn is pressed.
$("#more_posts").attr("disabled",true); // Disable the button, temp.
$.post(ajaxUrl, {
action:"more_post_ajax",
offset: (page * ppp) + 1,
ppp: ppp
}).success(function(posts){
page++;
$(".tabgrid").append(posts); // CHANGE THIS!
$("#more_posts").attr("disabled",false);
});
});
can anyone see what could be wrong here?
Your anchor is just a normal anchor and href="#" means scroll to top. Your JS code is trying to add a handler to and element with the id "#more_posts" but your anchor doesn't have an id.
Try replacing your anchor with <div id="more_posts">Load More</div>
In my WP Template I created two Sub fields in my Repeater custom fields for bg imgs:
The large device and desktop bg
The mobile bg
In my content-section.php template part, I created a loop and inject get_sub_field('background_image'); as a bg image successfully. I'd like to dynamically change the bg-img to mobile when the width is < 768. I know you have to pass the php data over to js by using wp_localize_script() etc..
What I've tried:
Set a var for get_sub_field('mobile_background_image'); in content-section.php
Used different variation of AFC Functions to pull bg data in functions.php: the_field('mobile_background_image'), get_sub_field('mobile_background_image'), the_sub_field('mobile_background_image'); but don't even see any data pulled when I console.log() the var, the most I get is null
Wrote my .each() multiple ways:
// Attempt #1
$('.bg-img').each(function() {
if($(window).width() < 768) {
var bgUrl = 'url("' + php_vars.mobile_bg + '") center center no-repeat)'
var style = {
'background': bgUrl,
'background-size': 'cover'
}
$('.bg-img').css(style);
}
});
// Attempt #2
if($(window).width() < 768) {
$('.bg-img').each(function() {
var bgUrl = 'url("' + php_vars.mobile_bg + '") center center no-repeat)'
var style = {
'background': bgUrl,
'background-size': 'cover'
}
$('.bg-img').css(style);
});
}
Also variations where $('.bg-img').css(style); was completely outside the function.
Question(s): For some reason I am not seeing any change when I inspect nor any console errors. How can I properly pull the sub_field data and pass that to and from my functions.php to my scripts.js and once that data is pulled and set in a var is my current function using .each() if(); etc... correct?
Content-section.php
<?php if( have_rows('section_content') ): ?>
<?php while( have_rows('section_content') ): the_row();
$sectionBG = get_sub_field('background_image');
$sectionContent = get_sub_field('section_text');
?>
<?php if( $sectionBG ): ?>
<div style="background: url('<?php echo $sectionBG ?>') center center no-repeat; background-size: cover;" class="full-height v-center-content bg-img">
<?php endif; ?>
<div class="container animation-element">
<div class="row">
<?php if(get_row_index() % 2 == 0) : ?>
<div class="col-12 col-md-6 offset-md-6 col-xl-5 offset-xl-7">
<?php else : ?>
<div class="col-12 col-md-6 col-xl-5">
<?php endif; ?>
<div class="section-content">
<?php echo $sectionContent ?>
</div>
</div>
</div>
</div>
<?php if( $sectionBG ): ?>
</div>
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>
Function.php
wp_enqueue_script('main-js', get_template_directory_uri() . '/js/script.js', array('jquery'), '', true);
wp_localize_script('main-js', 'php_vars', array(
'mobile_bg' => get_sub_field('mobile_background_image')
));
}
Script.js
$('.bg-img').each(function() {
if($(window).width() < 768) {
var bgUrl = 'url("' + php_vars.mobile_bg + '") center center no-repeat)'
var style = {
'background': bgUrl,
'background-size': 'cover'
}
$('.bg-img').css(style);
}
});
This is the role of CSS media queries.
In your main style sheet you would have
background-image: url('pic1.jpg');
In your mobile css file you would have
background-image: url('pic2.jpg');
In your html you would have
<link rel="stylesheet" href="style.css" type="text/css">
<link rel="stylesheet" href='mobile.css" type="text/css" media="only screen and (max-device-width:768px)">
$(window).on('resize', function () {
if($(this).width() < 768)
{
('.bg-img').each(function() {
var bgUrl = 'url("' + php_vars.mobile_bg + '") center center no-repeat)'
var style = {'background': bgUrl,
'background-size': 'cover'};
$(this).css(style);
});
}
});
This question might be old - but you can just install the mobble plugin - this tells you what kind of device in on you page - it also adds a class for the body.
Then you can simply use the plugins core functions -
<?php
//is_handheld(); // any handheld device (phone, tablet, Nintendo)
//is_mobile(); // any type of mobile phone (iPhone, Android, etc)
//is_tablet(); // any tablet device
//is_ios(); // any Apple device (iPhone, iPad, iPod)
/*is_iphone();
//is_ipad();
//is_ipod();
//is_android();
//is_blackberry();
//is_opera_mobile();
//is_symbian();
//is_kindle();
//is_windows_mobile();
//is_motorola();
//is_samsung();
//is_samsung_tablet();
//is_sony_ericsson();
//is_nintendo(); */
if(is_mobile()) {
$bgURL = get_sub_field("your mobile image here");
} else {
$bgURL = get_sub_field("your desktop image here");
}
Read more about the plugins functions and download here : https://wordpress.org/plugins/mobble/
After much tinkering I have found a solution that allows me to dynamically pull in the ACF data within a repeater field from my functions php and use in my script.js
The issue was that I was trying to pull the get_sub_field() data without running the has_rows loop, hence why I was receiving no data.
Updated functions.php
$php_vars = array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'root_dir' => get_template_directory_uri()
);
if (have_rows('section_content')) :
while (have_rows('section_content')) : the_row();
$mobile_url[] = get_sub_field('mobile_background_image');
$php_vars['mobile_bg'] = $mobile_url;
endwhile;
endif;
print_r($php_vars);
wp_localize_script('main-js', 'php_vars', $php_vars);
Within my functions.php I created a have_loop- more info here - to check if I have the repeater field on the page, if so, set the mobile image url(s) as an array. After that, I create a multidimensional array and add that to my $php_vars.
Updated script.js
if ($(window).width() < 768) {
var bgIMG = php_vars.mobile_bg;
var i;
console.log(bgIMG);
for ( i = 0; i < bgIMG.length; i++) {
$('.bg-img').attr('style', 'background: url("'+ bgIMG[i] +'") center center no-repeat; background-size: cover;');
}
}
After successfully testing that the url(s) were being stored as an array via print_r($php_vars); I'm able to called that data into my script and storing it into a var bgIMG. Testing to see if the data is still intact using console.log(bgIMG), I create a for loop to to add the data into my background url and increment.
This is the solution I figured out that seems to work. If anyone has a better solution or advice on how to improve this, I'm all ears.
I have a Tumblr-like blog feature that displays an image followed by some text in a div. This is repeated for as many posts as the the custom post-type contains using a loop, like so:
<?php
// The Arguments
$args = array(
'post_type' => 'strange',
'posts_per_page' =>-1,
'order_by' => 'menu_order'
);
$c = 0; // this starts the count at the beginning
$class = ''; // standard is no class
// The Query
$the_query = new WP_Query( $args ); ?>
<?php
// If we have the posts...
if ( $the_query->have_posts() ) : ?>
<!-- Start the loop the loop -->
<?php while ( $the_query->have_posts() ) : $the_query->the_post();
$c++; // this makes the loop count each post
if ( $c == 1 ) $class .= ' current'; // if the item is the first item, add class current
else $class = ''; // if it's not the first item, don't add a class
?>
<div id="strange-container" class="strange-container <?php echo $class; ?>">
<img src="<?php the_field('strange-img'); ?>" alt="<?php the_title(); ?>" />
<span><?php the_field('strange-text'); ?></span>
</div>
<?php endwhile; endif; // end of the loop. ?>
<?php wp_reset_postdata(); ?>
I have a navigation arrow at the top of the page. On click, I want it to scroll the user to the div in the loop. I have this working using this jQuery that adds a class/removes a class from each div as you click the arrow:
jQuery(document).ready(function($) {
// Code that uses jQuery's $ can follow here.
$('div.strange-container').first();
$('a.display').on('click', function(e) {
e.preventDefault();
var t = $(this).text(),
that = $(this);
if (t === '↓' && $('.current').next('div.strange-container').length > 0) {
var $next = $('.current').next('.strange-container');
var top = $next.offset().top;
$('.current').removeClass('current');
$('html, body').animate({
scrollTop: top
}, function () {
$next.addClass('current');
}); // not using this portion for a previous button but left it in anyway just in case
} else if (t === 'prev' && $('.current').prev('div.strange-container').length > 0) {
var $prev = $('.current').prev('.strange-container');
var top = $prev.offset().top;
$('.current').removeClass('current');
$('body').animate({
scrollTop: top
}, function () {
$prev.addClass('current');
});
}
});
});
The problem:
Once the user clicks all the way through the existing posts on the page, the arrow doesn't reset and no longer works, even if the user scrolls back up to the top of the page. Is there another way to accomplish this that wouldn't render the down-arrow navigation useless after the user has gone all the way through the posts once?
Or, is there a way to hide the down-arrow navigation once the user has scrolled to the bottom of the page (or navigated through all of the posts)?
After many hours of looking for an appropriate solution, I stumbled on this thread: Scroll to div on click, loop around at end
I modified the fiddle, and it works perfectly for my purposes:
https://jsfiddle.net/9x335kzg/25/
var curr_el_index = 0;
var els_length = $(".section").length;
$('.btnNext').click(function () {
curr_el_index++;
if (curr_el_index >= els_length) curr_el_index = 0;
$("html, body").animate({
scrollTop: $(".section").eq(curr_el_index).offset().top - 20
}, 700);
});
If someone wouldn't mind explaining to me how this script forces the looping when the user clicks to the end of the divs, I'd really appreciate learning more about this solution I stumbled upon.
I've had a look through the old questions and tried many of the different methods that there seems to be to do this. The closest I've got to working is this one here: How to implement pagination on a custom WP_Query Ajax
I've tried everything and it just doesn't work. Absolutely nothing changes on the page. If you inspect the Load More Button and click it, the jQuery is making the Load More Button action as it changes from <a id="more_posts">Load More</a> to <a id="more_posts" disables="disabled">Load More</a> which even that doesn6't seem right to me anyway. It's not adding the posts, I think I'm missing something simple but for the life of me I can't work it out.
The code in my template file is:
<div id="ajax-posts" class="row">
<?php
$postsPerPage = 3;
$args = [
'post_type' => 'post',
'posts_per_page' => $postsPerPage,
'cat' => 1
];
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post(); ?>
<div class="small-12 large-4 columns">
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
</div>
<?php
endwhile;
echo '<a id="more_posts">Load More</a>';
wp_reset_postdata();
?>
</div>
The code in my functions file is:
function more_post_ajax(){
$offset = $_POST["offset"];
$ppp = $_POST["ppp"];
header("Content-Type: text/html");
$args = [
'suppress_filters' => true,
'post_type' => 'post',
'posts_per_page' => $ppp,
'cat' => 1,
'offset' => $offset,
];
$loop = new WP_Query($args);
while ($loop->have_posts()) { $loop->the_post();
the_content();
}
exit;
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
And my jQuery in the footer is:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
jQuery(document).ready( function($) {
var ajaxUrl = "<?php echo admin_url('admin-ajax.php')?>";
// What page we are on.
var page = 5;
// Post per page
var ppp = 3;
$("#more_posts").on("click", function() {
// When btn is pressed.
$("#more_posts").attr("disabled",true);
// Disable the button, temp.
$.post(ajaxUrl, {
action: "more_post_ajax",
offset: (page * ppp) + 1,
ppp: ppp
})
.success(function(posts) {
page++;
$("#ajax-posts").append(posts);
// CHANGE THIS!
$("#more_posts").attr("disabled", false);
});
});
});
</script>
Can anybody see something I'm missing or able to help?
UPDATE 24.04.2016.
I've created tutorial on my page https://madebydenis.com/ajax-load-posts-on-wordpress/ about implementing this on Twenty Sixteen theme, so feel free to check it out :)
EDIT
I've tested this on Twenty Fifteen and it's working, so it should be working for you.
In index.php (assuming that you want to show the posts on the main page, but this should work even if you put it in a page template) I put:
<div id="ajax-posts" class="row">
<?php
$postsPerPage = 3;
$args = array(
'post_type' => 'post',
'posts_per_page' => $postsPerPage,
'cat' => 8
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<div class="small-12 large-4 columns">
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
</div>
<?php
endwhile;
wp_reset_postdata();
?>
</div>
<div id="more_posts">Load More</div>
This will output 3 posts from category 8 (I had posts in that category, so I used it, you can use whatever you want to). You can even query the category you're in with
$cat_id = get_query_var('cat');
This will give you the category id to use in your query. You could put this in your loader (load more div), and pull with jQuery like
<div id="more_posts" data-category="<?php echo $cat_id; ?>">Load More</div>
And pull the category with
var cat = $('#more_posts').data('category');
But for now, you can leave this out.
Next in functions.php I added
wp_localize_script( 'twentyfifteen-script', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'noposts' => __('No older posts found', 'twentyfifteen'),
));
Right after the existing wp_localize_script. This will load WordPress own admin-ajax.php so that we can use it when we call it in our ajax call.
At the end of the functions.php file I added the function that will load your posts:
function more_post_ajax(){
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 3;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
header("Content-Type: text/html");
$args = array(
'suppress_filters' => true,
'post_type' => 'post',
'posts_per_page' => $ppp,
'cat' => 8,
'paged' => $page,
);
$loop = new WP_Query($args);
$out = '';
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
$out .= '<div class="small-12 large-4 columns">
<h1>'.get_the_title().'</h1>
<p>'.get_the_content().'</p>
</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');
Here I've added paged key in the array, so that the loop can keep track on what page you are when you load your posts.
If you've added your category in the loader, you'd add:
$cat = (isset($_POST['cat'])) ? $_POST['cat'] : '';
And instead of 8, you'd put $cat. This will be in the $_POST array, and you'll be able to use it in ajax.
Last part is the ajax itself. In functions.js I put inside the $(document).ready(); enviroment
var ppp = 3; // Post per page
var cat = 8;
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();
});
Saved it, tested it, and it works :)
Images as proof (don't mind the shoddy styling, it was done quickly). Also post content is gibberish xD
UPDATE
For 'infinite load' instead on click event on the button (just make it invisible, with visibility: hidden;) you can try with
$(window).on('scroll', function () {
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
load_posts();
}
});
This should run the load_posts() function when you're 100px from the bottom of the page. In the case of the tutorial on my site you can add a check to see if the posts are loading (to prevent firing of the ajax twice), and you can fire it when the scroll reaches the top of the footer
$(window).on('scroll', function(){
if($('body').scrollTop()+$(window).height() > $('footer').offset().top){
if(!($loader.hasClass('post_loading_loader') || $loader.hasClass('post_no_more_posts'))){
load_posts();
}
}
});
Now the only drawback in these cases is that you could never scroll to the value of $(document).height() - 100 or $('footer').offset().top for some reason. If that should happen, just increase the number where the scroll goes to.
You can easily check it by putting console.logs in your code and see in the inspector what they throw out
$(window).on('scroll', function () {
console.log($(window).scrollTop() + $(window).height());
console.log($(document).height() - 100);
if ($(window).scrollTop() + $(window).height() >= $(document).height() - 100) {
load_posts();
}
});
And just adjust accordingly ;)
Hope this helps :) If you have any questions just ask.
If I'm not using any category then how can I use this code? Actually, I want to use this code for custom post type.