Load Next WordPress Posts With AJAX
241Today, we’re going to replace the standard “Older Posts” links on your blog. Our plugin will create a button to instantly load the next page of posts, without reloading the page (Similar to what Twitter used to do at the bottom of profiles)
Update (1 March 2018): Demo site taken down. Screenshot above shows how the button looks, posts then load seamlessly in place, as though there had always been 20 posts on the page rather than just 10.
You can also download the completed files as a plugin here (Just upload and activate it).
Now, let’s get started. Our plugin is going to have several features:
- Multiple clicks – First clicks will load page 2’s posts, second will load page 3 etc.)
- Check for posts first – If there are no more posts that can be loaded, we’ll tell the user.
- Degrade gracefully – If a visitor doesn’t use JavaScript, we won’t change the site at all.
Plugin Structure
There will be 3 files in this plugin (One PHP, one CSS, one JS). For good practice, we’ll keep the CSS and JavaScript in their own folders.
And I’ve called the plugin “pbd-ajax-load-posts”.
Now let’s start by putting the necessities at the top of our pbd-ajax-load-posts.php file:
1 2 3 4 5 6 7 8 9 10 | <?php /** * Plugin Name: PBD AJAX Load Posts * Plugin URI: http://www.problogdesign.com/ * Description: Load the next page of posts with AJAX. * Version: 0.1 * Author: Pro Blog Design * Author URI: http://www.problogdesign.com/ * License: GPLv2 */ |
All good so far? Cool, time to get started for real.
Loading Files and Passing Values
The first thing we need to do is ensure that our JavaScript and CSS files are loaded on the right pages. Stay in the pbd-ajax-load-posts.php file and paste this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | /** * Initialization. Add our script if needed on this page. */ function pbd_alp_init() { global $wp_query; // Add code to index pages. if( !is_singular() ) { // Queue JS and CSS wp_enqueue_script( 'pbd-alp-load-posts', plugin_dir_url( __FILE__ ) . 'js/load-posts.js', array('jquery'), '1.0', true ); wp_enqueue_style( 'pbd-alp-style', plugin_dir_url( __FILE__ ) . 'css/style.css', false, '1.0', 'all' ); |
The code above begins by creating a new function, pbd_alp_init() (alp = AJAX Load Posts), which we will then hook into place later on.
You’ll notice that we also call the global $wp_query variable, which we’ll use in the next step.
The important parts begin on line 8. The first statement is a conditional statement. It means that on any page that isn’t an individual post or Page, we are going to run this code.
This is a broad brush to make sure our code runs on the homepage, tag pages, search pages etc. You can adapt it to be more specific, e.g. if you don’t want the code included on your homepage.
We then use wp_enqueue_script() and wp_enqueue_style() to tell WordPress about our two files (As well as the fact that we will be using jQuery).
Now, we need to pass some values to our script, namely:
- The page number we’re on right now (Going to page 1 99% of the time, but let’s be sure).
- The total number of pages (So we know when we’ve hit the limit).
- The link to the next page (e.g. site.com/tag/example/page/2/)
We will use the wp_localize_script() function to calculate each of these values in PHP, and then print them into the webpage so that our script can access them later (Hat tip to Professional WordPress Plugin Development for introducing me to this great function!)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | // What page are we on? And what is the pages limit? $max = $wp_query->max_num_pages; $paged = ( get_query_var('paged') > 1 ) ? get_query_var('paged') : 1; // Add some parameters for the JS. wp_localize_script( 'pbd-alp-load-posts', 'pbd_alp', array( 'startPage' => $paged, 'maxPages' => $max, 'nextLink' => next_posts($max, false) ) ); |
We begin by working out the first 2 values. $max is the maximum number of pages the current query can return (e.g. if each page shows 5 posts and there are 12 posts in the current category, then max will be 3).
The $paged variable will store the page we are currently on (The whole point of our plugin is to ensure people never load a second page, but it doesn’t hurt to make sure).
If you skip down to line 12, you’ll see where I’ve worked out the 3rd value (The link to the next page). next_posts() is a built-in WordPress function that will return the URL we need.
The wp_localize_script() function is great because it makes it easy to pass values from PHP to JavaScript. The first value, ‘pbd-alp-load-posts’ must match the first value in the wp_enqueue_script() call.
The second value, ‘pbd_alp’, is the name we will use in our JavaScript later on.
Finally, we send over an array of the data. If you view the HTML source of your webpage later, you’ll see something like this right before your JavaScript file is loaded:
1 2 3 4 5 6 7 8 9 | <script type='text/javascript'> /* <![CDATA[ */ var pbd_alp = { startPage: "1", maxPages: "6", nextLink: "http://www.problogdesign.com/demo/ajax-load-posts/page/2/" }; /* ]]> */ </script> |
Now, we just need to close up our if statement, our pbd_alp_init() function, and then hook it all into place.
1 2 3 | } } add_action('template_redirect', 'pbd_alp_init'); |
We use the template_redirect hook because with the init hook, the $wp_query variable won’t be set yet.
jQuery – The Heart of our Plugin
We have now loaded our scripts and passed the values we need. It’s time to get to the real meat of our tutorial.
Open the load-posts.js file. The first thing we do is access the 3 variables we passed in with our PHP function.
1 2 3 4 5 6 7 8 9 10 | jQuery(document).ready(function($) { // The number of the next page to load (/page/x/). var pageNum = parseInt(pbd_alp.startPage) + 1; // The maximum number of pages the current query can return. var max = parseInt(pbd_alp.maxPages); // The link of the next page of posts. var nextLink = pbd_alp.nextLink; |
The way to access our values is to use the format: pbd_alp.valueName (pbd_alp was the second value we entered in wp_localize_script(), remember?).
The important thing to remember is that our numbers have been sent over as strings, so we use JavaScript’s parseInt() function to convert them back to numbers.
With pageNum, we add one to the number because it is going to store the number of the next page to load (Not the current page).
Most themes already have navigation to move between pages, in the form of Older Posts/Newer Posts links. We want to replace that with our AJAX button, so our first step will be to remove those navigation links, and insert our button instead.
1 2 3 4 5 6 7 8 9 10 11 12 13 | /** * Replace the traditional navigation with our own, * but only if there is at least one page of new posts to load. */ if(pageNum <= max) { // Insert the "More Posts" link. $('#content') .append('<div class="pbd-alp-placeholder-'+ pageNum +'"></div>') .append('<p id="pbd-alp-load-posts"><a href="#">Load More Posts</a></p>'); // Remove the traditional navigation. $('.navigation').remove(); } |
We start out with a conditional check. Remember that pageNum is the number of the next page, so if it is greater than max, there are no more pages to load. In that case, we don’t want to add the button.
If there is new content to load though, then we look for the #content div, and add two things to the end of it. The first is an empty div, which we will later use to insert our posts into.
The second is the button itself (A regular HTML link), wrapped up in a paragraph.
Finally, we look for the .navigation div and remove it. If your theme uses a different class for the navigation buttons, you will need to change that (.navigation is the default that the 2010 theme uses). The same thing applies to the #content div too!
The result of the code above is that our button is now in place, though it won’t do anything yet.
And because we did it all with JavaScript, we know our plugin degrades gracefully (Because if the JavaScript isn’t loaded, no changes will be made to the page).
Now, let’s take care of what happens when the user actually clicks the button.
1 2 3 4 5 6 7 8 9 10 | /** * Load new posts when the link is clicked. */ $('#pbd-alp-load-posts a').click(function() { // Are there more posts to load? if(pageNum <= max) { // Show that we're working. $(this).text('Loading posts...'); |
The first line of code is a jQuery event handler, which runs when a user clicks the button.
On line 7, we run the same check as before. This is important because our script would load in a 404 error message if there were no more posts. Definitely not what we want!
Line 10 updates the text on our button to read “Loading posts…” This is good practice because users will get an instant reaction when they click the button.
The next step is to make the AJAX call. Quite a lot happens here, so copy and paste the following into your script and I’ll walk through it all afterwards.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | $('.pbd-alp-placeholder-'+ pageNum).load(nextLink + ' .post', function() { // Update page number and nextLink. pageNum++; nextLink = nextLink.replace(/\/page\/[0-9]?/, '/page/'+ pageNum); // Add a new placeholder, for when user clicks again. $('#pbd-alp-load-posts') .before('<div class="pbd-alp-placeholder-'+ pageNum +'"></div>') // Update the button message. if(pageNum <= max) { $('#pbd-alp-load-posts a').text('Load More Posts'); } else { $('#pbd-alp-load-posts a').text('No more posts to load.'); } } ); |
The first line is the most important. We use a jQuery selector to select our placeholder div. The reason we have added the pageNum number to the end of the class name is so that if the user clicks the button again, we’ll add the new posts to a new placeholder (Not overwrite the old one).
The .load() function loads the URL we pass (Remember that nextLink is the URL for the next page), and because we have added .post to the end, it will only copy over the .post divs that it finds (Not the whole page!)
On line 2, we start a new function which will run when the AJAX call completes. The first thing it does is update our values for the next time the button is clicked.
pageNum is increased by one (To point to the new next page), and nextLink is updated using a regular expression. This searches the URL for /page/2/ (Or any number), and replaces the number portion with the new next page number.
On line 8, we add a new placeholder div. This will be used the next time the button is clicked.
Finally, on line 12, we update the text on the button again. If there are more posts that can be loaded, we revert back to the original text. If there aren’t, then we’ll update with a message saying so.
Now, we just need to round things off:
1 2 3 4 5 6 7 | } else { $('#pbd-alp-load-posts a').append('.'); } return false; }); }); |
This code begins by closing off the first if-statement (Are there more pages to load?). If there aren’t, it adds a ‘.’ to the button’s message. This is simply to give some sort of visual response to the user when the button is clicked (Look at the screenshot below to see what happens).
And last of all, we use return false; to prevent the link from the button itself loading.
Style It
Your button is now fully working! The only thing remaining is to style it. You can do this however you like with CSS. I’ve used CSS3 to round off the corners, and add a gradient and drop shadow.
You can look these up more online (Or post in the comments if you’d like to see some CSS3 tuts here), but a big thanks is due to CSS Tricks for making the cross-browser gradient code easy.
Add this to your css/style.css file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 | #pbd-alp-load-posts a:link, #pbd-alp-load-posts a:visited { display: block; text-align: center; padding: 4px 0; color: #444; text-decoration: none; /** Rounded Corners **/ -moz-border-radius: 8px; border-radius: 8px; /** Drop shadow **/ -moz-box-shadow: 1px 1px 1px #999; -webkit-box-shadow: 1px 1px 1px #999; box-shadow: 1px 1px 1px #999; /** Gradients : http://css-tricks.com/css3-gradients/ */ /* fallback */ background-color: #f1f1f1; /* Firefox 3.6+ */ background: -moz-linear-gradient(100% 100% 90deg, #e4e3e3, #f1f1f1); /* Safari 4-5, Chrome 1-9 */ /* -webkit-gradient(<type>, <point> [, <radius>]?, <point> [, <radius>]? [, <stop>]*) */ background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#f1f1f1), to(#e4e3e3)); /* Safari 5.1+, Chrome 10+ */ background: -webkit-linear-gradient(#f1f1f1, #e4e3e3); /* Opera 11.10+ */ background: -o-linear-gradient(#f1f1f1, #e4e3e3); } #pbd-alp-load-posts a:hover, #pbd-alp-load-posts a:active { /** Drop shadow **/ -moz-box-shadow: 1px 1px 1px #bbb; -webkit-box-shadow: 1px 1px 1px #bbb; box-shadow: 1px 1px 1px #bbb; /** Gradients : http://css-tricks.com/css3-gradients/ */ /* fallback */ background-color: #f5f5f5; /* Firefox 3.6+ */ background: -moz-linear-gradient(100% 100% 90deg, #eaeaea, #f5f5f5); /* Safari 4-5, Chrome 1-9 */ /* -webkit-gradient(<type>, <point> [, <radius>]?, <point> [, <radius>]? [, <stop>]*) */ background: -webkit-gradient(linear, 0% 0%, 0% 100%, from(#f5f5f5), to(#eaeaea)); /* Safari 5.1+, Chrome 10+ */ background: -webkit-linear-gradient(#f1f1f1, #eaeaea); /* Opera 11.10+ */ background: -o-linear-gradient(#f5f5f5, #eaeaea); } |
And that’s you done! Just save your work and activate the plugin.
If you have any issues, check that your theme uses the #content and .navigation divs in the way that we assumed. Most themes will, but not all. If yours is different, update those values in the JavaScript file.
Let me know what you thought of the effect! And don’t forget you can grab the completed plugin here.
And if you have any feedback on the tutorial, I’d love to hear it! Too long? Or more explanation needed? (The demo site exists now purely because some of you asked for it in previous tutorials, so thank you!)
Enjoy this post? You should follow me on Twitter!
Looks cool, any plans to add it in WordPress plugin directory? or are there some submitted already?
I was thinking about doing this. I had a quick look, and there aren’t really any.
The only reason I haven’t submitted it just yet is that to be compatible with more themes, it would need an options page to let users change the #content and .post selectors used if they needed to.
If the script does work out popular enough though, then I’ll definitely do that! :)
Very, very nice Michael! I love that you’ve taken the time to explain the script localization! That’s something very, very few people have taken the time to do well.
Thanks Pippin! I hadn’t seen the trick before until I came across it in the Pro WP Plugin dev book. It’s a really fantastic use of that function though, extremely handy!
So agree, the explanations are very useful! Well done.
Very interesting. But wont this approach have a negative impact on SEO?
Interesting question. I wouldn’t have thought so though. The original links are only taken out by JavaScript, so the search engines should still be able to find them.
(That said, it would definitely be interesting to hear an SEM’s view on search engines and AJAX)
Very cool! One bug I noticed though: When there are no posts left, and you continue to click the button, it adds a period to the end of the button text each time you click…any ideas why?
Thanks for the comment Chris. I set that up deliberately. My reasoning was that it was good just to show some sort of response.
Instead of a user hitting it and nothing happens (In which case, you might wonder about your net connection or the server), you see a new dot appear (Which should hopefully draw your attention to the message on the button, indicating why nothing is happening).
If you wanted to change that, look for this near the bottom of the jQuery script:
$(‘#pbd-alp-load-posts a’).append(‘.’);
Or you could go the sarcastic route.
$(‘#pbd-alp-load-posts a’).html(‘I said there were no more posts to load…’);
Haha, I like that approach Matt! Maybe give it an angry red background too… :D
Nice Michael great tutorial,
Thanks Kevin! :)
Hi Michael, would it be possible to modify the plugin so that instead of having to click the button, just scrolling to the bottom of the page would automatically load the additional posts? I believe I’ve seen that on several other websites but unfortunately I can’t remember where it was right now.
Thanks
Maria
Hi Maria,
Yep, I could definitely do that. Twitter itself does it this way now.
I’ll see about giving it a go and writing it up in a tutorial soon! :)
Such a great idea. I hope Martin can write up a tutorial for this. Even facebook is using the same method.
Any news on the automatic load?
Would love to see the auto load implemented too.
I also would like it
Neat script, Michael.
So how did you set up your new demo site? Are you using the multisite functionality so you can just create fresh WordPress instances with a few clicks? Or are you doing something else?
Yep, using a multisite install. It should make maintaining it quite a bit easier because if I want to upgrade WordPress, it only needs to be done in one place. With individual installs, I’d never manage to keep up with it.
Very, very nice Michael! A great post. That’s something very, very few people have taken the time to do well.
Thanks Michael Martin ! which can be applied to wp mu is not?
Great plugin I just started using it as well. But something is wrong with the completed version though. It loads up everything but the styling doesnt seem to appear only a text with “Load More Posts”. Is there a way to complete it?
I installed the plugin normally, I activated and everything, but in my theme doesn’t appear. Then I activate the default theme of WordPress (Twenty) and appears normally.
I’m testing it on WordPress 3.2 RC1 on my localhost.
Thanks :)
Hey there Micheal, great plugin!
Thanks for sharing.
I do have the same problem as Gustavo. I intend to use the plugin in a custom template but it fails to display, even though the javascript does load. But if tested with the Twenty Ten theme activated it works great.
Any ideas what might be going on?
:)
Hey Micheal, Gustavo!
I found what was the problem… so here it is for further documentation…
in load-posts.js line 16 the if statement needs to locate the div with id=content, so if your template does not have it the button will not show… so change the line $(‘#content’) for your div’s id or include a wrapper with that id.
I hope you find this usefull.
:)
Glad yous found the issue. That’s why I haven’t released this as a plugin on WP.org yet. It does need to be tweaked slightly to suit your theme.
#content is the convention, because it’s used in the default theme. But that definitely doesn’t guarantee that every theme will use it (Or even that they’re wrong to, because most of the time it doesn’t matter!)
very nice plugin, i downloaded it and installed on my home pc having xampp server, but under wordpress iam unable to see its effects even after activating from the wp control panel
A really cool plugin – thanks Michael!
Hi there, i used your plugin at my new blog, its wonderfull!!! Just need a simple adjust to use in WP versions plus 3.1.
Newer paginations seems to be changed, not more like that: /page/9 but like this: ?paged=9.
I used this new RegEx /paged[=].[0-9]?/ instead /\/page\/[0-9]?/ and works fine to me.
Thak u Michael for share, i just luved it.
Thanks, this fix worked for me too.
The whole line should be replaced with
nextLink = nextLink.replace(/paged[=].[0-9]?/, ‘paged=’+ pageNum);
Not working?
To those reading this on WP 3.1 or above, the fix above is indeed very important for the script to load posts beyond page 2 (because of the new pagination format).
Note that, while the code from Peter is correct, it has been corrupted by the comment system. If you copy the line verbatim, you will get argument errors.
I’ve fixed the code and pasted it here:
http://pastebin.com/ia8pZYwD
Copy that and replace line 42 in the Javascript file.
Just an update: on my local installation I changed my permalinks settings, which meant I had to change line 42 back to its original code for it to work. So I assume, the above fix is for those who use the default permalinks settings but not for those who have a different setting.
“Very interesting. But wont this approach have a negative impact on SEO?” same problem with me
Really good tutorial. This easy to understand..
Doing good job:-)
Thanks a lot..!
Hi ,
I have s:file upload tag in my jsp.and one sx:autocompleter tag.
if i change the element in sx:autocompleter the ajax to work.
But the s:file tag is preventing not to work ajax properly.
Can you give me some idea.Pls…..
Im trying this for past one week…..
Thanks in advance.
Hey Micheal!
… I really like this tutorial man, great job!
I’ve got a question… I’m using the ShareThis plugin, and my guess is that the Facebook and Twitter buttons and counters are loaded via javascript.
So whenever the Load More Post button is pressed it does loads more posts but without the ShareThis buttons, so I guess this would happen with any other thing that might be loaded into the post via javascript…
so my question is… How to load everything that might be loaded via javascript into the post, whenever the Load More Posts button is clicked?
thanks!
:)
I had the same problem. Not solved yet…
Same issue. Did you guys ever figure it out? Any help would be appreciated. Overall great plugin, thanks for sharing!
Same problem here… I have a grid of posts with the post title fading in/out on mouseover with Javascript, however this only works for the first set. The rollover fails on any posts dynamically loaded with the plugin.
Advice appreciated!
Cheers.
Further to my comment above, I my [fairly basic] jquery stuff to work on the ajax-loaded content by using .live() – recommend you take a look.
http://api.jquery.com/live/
same problem… did you find a solution?
Has there been any solution to the ShareThis bug? Everything works great except for this error.
Judging by the comments and no update from Mike, this might be a lost cause just by how this method works. Too bad…
So useful tutorial. Thank you ;)
same problem… did you find a solution?
very useful article. But it would be better if the button was inserted with javascript, or if the button linked to the page with older posts. A dead button isn’t very user friendly.
I did another usefull change to detect the Template being used and only show the Load button at Default Template, excluding mobile templates, for example, don’t load unused buttons anymore.
I spent like 2 hours trying to make it work. Could you provide a checklist of necessary things to make it work please ?
It looks so good, it makes me sad.
Thanks Michael Martin ! It looks so good,
Really useful post, thanks for going into so much detail, i’ve been meaning to try this out on some of my blogs but i’ve never quite worked out how to do it!
Thank for tutorial. I love this blog so much.
Hi Michael,
Thank You for this greate blog. This is a nice plugin, and i works perfectly when i use Twentyten. Right now I am working on my own theme, and I want to use this plugin, but I cannot make it work. Here is a link for my website: http://www.bolbrobadminton.dk/arkiv/
Do you have any ideas of what to do?
I love the plugin, but I can’t it working correctly with my theme since it involves getting each post on separate placeholders in a grid view. The theme I use is http://themeforest.net/item/sidewinder-for-wordpress-dynamic-grid-portfolio/160721
if you resize your browser you would see that each post is in it’s own container. The theme uses for that container , so if i was to do a with some content inside of it right after the loop, that will move with the rest. The way it is now, it’s moving all the posts loaded in just one single container.
I changed it to this since it has a the grid-content after the content:
$(‘#content ul’) //same thing as $(‘#grid-content’)
.append(”);
$(‘#content’) //left this like this so it loads below everything
.append(‘Load More Posts‘);
it works but it loads it in one container instead of separate containers.How would I go by putting each post on it’s own container? Hoping it’s something simple that way I can use it on my theme. I tried different ways but no luck. I’m guessing I have to create a for loop somewhere saying for each post of that page loaded, put it on a container…
I guess this would be good for any other theme that has a preview of the post somewhere else in the page and not in a straight list. Any help will be appreciated.
I just noticed that what I posted didn’t show everything i posted, but on the second paragraph I said The theme uses an ‘ li ‘ tag as the container…. so if i was to do a ‘ li’ tag with some content inside of it right after the loop, that will move with the rest…
Hey Alex,
I was wondering did you figure out how to use this plugin for the grid theme?
I use the Shaken Grid theme.
http://www.dnykitchen.com/demo
Michael,
Can you also provide some suggestions?
Thanks!
Great tutorial! I got one question: Im building a new theme, so I am getting my blogpage trought ajax. So my url is allways http://localhost:8888/wordpress/ at the moment. but the real blogpage url is http://localhost:8888/wordpress/blogpage/page/1/, so i think the wp_localize_script fails at finding the startpage, maxpages and nextlink information. is it any way i can fix this. i can upload my theme up to a server if you want too see..
Michael, that’s cool! The result is amazing… makes me keep clicking on the “Load more posts” button! :)
Has anyone found a solution to bring the loaded posts with everything the post might have attached to it?
For example, all things a post may have loaded through javascript, let’s say mp3 players, social sharing iframes, counters, etc. etc.
Please help!!!
Hi,
I see that You in a earlier comment, write about using this plugin in a custom theme. I have problem using this on my own personal theme on this url: http://www.bolbrobadminton.dk/test/
Do you have any ideas of what I am doing wrong?
Michael, have you ever done this with a custom WP_Query(). I’ve been messing with it for a while now and not succeeding.
I think that is why im failing to :S
Hey Pippin,
I’ve been able to make this work with a custom query. I think the trick is making sure your custom query works with pagination in the first place. I’ve been able to do so by adding the following:
Declare the global “paged” variable in the template file on which you’re using the custom query (i usually put it at the top where i call the header:
global $paged;
Then add this parameter to your custom query arguments:
'paged' => $paged
Hope this helps.
After alot of fiddling i got it to work in my custom theme… sort of… When i click the “Load next posts” the firts time it loads 10 new posts. But when i click the second time it just repeats the recent 10 posts. I suspect i have the same problem as pippin and lasse.
Did you guys solve it, how did you?
Inside pbd-ajax-load-posts.php you have to add your new query as explained on http://codex.wordpress.org/Class_Reference/WP_Query. Just add your new args below the global, make sure this query matches your args for your template loop. Then change $wp_query on line 39 with your new query name. This should now follow the
new merged args.
Hope this helps…now maybe someone can help me with a different issue in my own reply further below :)
Regards,
Marius
You also have to add 406 media’s info to your args, at least on the template loop. That worked for me. You can also remove the global $wp_query from pbd-ajax-load-posts.php if you want as it is no longer needed.
I am trying it in default WP home page, it works fine. But I am using Custom Posts and it shows there in homepage. Any solution for that?
Thanks.
Tejas
I tried implementing it on one of my blogs but it messd up with widget display and made page loading time infinite on IE. Coudn’t figure out the problem and finally ended up restoring the original theme..
I tried pasting the plugin in my functions.php and scripts.js, but it doesn’t seem to work.
I solved the problem. It works.
How were you able to get it working?
Hi,
This is really very nice and usefull plugin. I used this plugin with custom theme which is the copy of default theme(twentyten). I used #content wherever it was required. Its working fine in all browser except IE. It is not loading the posts in the place holder div.
Any idea why it is happening ??
Thanks
Ravi
Yeah. I’m still having trouble. Works in all the other browsers except IE6 to IE8. It does work in IE9
If you will install this plugin in default theme then it will work in ie7 and ie8. It is not working with custom theme which is actually copy of default theme.
I found the culprit. Still working on how to fix it.
.load(nextLink + ‘ .post’, function()
Try removing + ‘ .post’ from the line above and it will work in IE7. The problem is that it will no longer filter the elements and outputs the whole page.
Anyone found the cure for the ie78 problem? My favourite solution is visibility:hidden and just forget about it for ie but if anyone has a better fix that would be an awesome bit of visibility: visible.
.load(nextLink + ‘ .post’, function()
try
.load(nextLink +’?fake=’ + pageNum + ‘ .post’ , function()
The problem with IE less than Ie 9 is that it cache the ajax request. So you need to add a dinamic number at the end of the link.
Hi Michael –
Fantastic post, a clear description of the process and clean code. It works flawlessly on my site with the Twenty-Eleven theme, but the jQuery doesn’t print to my own theme.
Very In-progress example of my theme here: http://triviumproject.com/category/movement/neoclassicism/
I’ve changed the #content div, but it seems like the javascript just isn’t getting pulled in at all – any ideas what I’m missing? Thanks again for your exceptional work, any advice would be deeply appreciated.
Hi Reed,
There is one .php file in the plugin. In this file the javascript and css file is being loaded. You will find there a condition for loading js and css file in only one page.You can put your condition for loading those files in other pages as well.
“if( !is_singular()) { ” This is the condition. You can modify it by putting another condition.
Thanks
Ravi
Hi,
I was wondering how to implement to my sidebar.php and archive.php. I download the plugin and activated but nothing is happening.
my siderbar.php is like youtube with list of related videos to the main content. I would like to able to load only 10 of them with “load more” option.
Could you please show me how? thanks
Change the “?” in the
nextLink = nextLink.replace(/\/page\/[0-9]?/, ‘/page/’+ pageNum);
section to a “+” so it reads:
nextLink = nextLink.replace(/\/page\/[0-9]+/, ‘/page/’+ pageNum);
that got it working to add more than 10 for me
Hi,
In my sidebar.php I have and I have already modified in “load_post.js”
if(pageNum <= max) {
// Insert the "More Posts" link.
$('.single_sidebar_right')
.append('’)
.append(‘Load More Posts‘);
// Remove the traditional navigation.
$(‘.Nav’).remove();
}
but still not working. is there anything that I’m missing?
thanks
Thanks Michael Martin ! which can be applied to wp mu is not?
Hey Michael,
Super awesome tutorial. I am also reading WP Pro Plugin Development and thus I appreciate your efficient and neat coding techniques. I have a small correction regarding your regular expression that you use to get the “next link” Rather than:
nextLink.replace(/\/page\/[0-9]?/, '/page/'+ pageNum);
It should be:
nextLink.replace(/\/page\/[0-9]*/, '/page/'+ pageNum);
This will ensure that you can load pages beyond page 10. Thanks again for the awesome tutorial! It got me 99.99% of the way there. haha. All the best.
-Jeff
This is a great one..nice article, thanks for share with us… I learn a lot with your words.. thank for the post.
This might help some people…
I had to add the following bits to my custom theme.
I put that immediately after the Loop.
And put this right after it. I am writing my theme from scratch and didn’t yet have any page navigation.
Finally, I had to add
class="post"
to my post container in the Loop. My post container is anelement and it didn’t have any ID or classes yet and I am not using
in my template.
My theme is very custom and therefore doesn’t have the standard code that is expected in a typical WordPress theme.
(Sorry, forgot to encode the HTML entities. Here it is again.)
<div id="content"></div>
I put that immediately after the Loop.
<div class="navigation"><?php next_posts_link('Older Entries →', 0); ?></div>
And put this right after it. I am writing my theme from scratch and didn’t yet have any page navigation.
Finally, I had to add
class="post"
to my post container in the Loop. My post container is an element and it didn’t have any classes yet because I am not using<?php post_class(); ?>
in my template.My theme is very custom and therefore doesn’t have the standard code that is expected in a typical WordPress theme. Adding these bits made the plugin work for me. Now I plan to integrate the plugin into my theme directly.
Gah…
My post container is an
<article>
element…Also, I have been trying to make it work for comments. However, in the functions.php function, I keep getting 0 for the total number of comments pages. So, the rest of the Javascript doesn’t work.
Anyone know why
$wp_query->max_num_comment_pages
doesn’t work within functions.php? It’s in the same function which already hasglobal $wp_query;
Also, I am wondering if the script can be changed to use a custom WordPress template that just has the trimmed down HTML. This would make it lighter.
Hi Luke,
Did you manage to get it to work with comments?
I’d like to have this functionality for comments too and was wondering if it can be achieved by hacking the plugin described here…
Please let me know if you have an idea.
Nice walkthrough. Being self-educated within web-development you need these kind of walkthrough and this one taught me what I needed regarding Ajax. Thanks.
Awesome tutorial Michael! I was looking for a tutorial to do this in PHP actually
Awesome tutorial Michael! I was looking for a tutorial to do this in PHP actually and found this. So skipped away the job of converting into a WP plugin. Thanks again. You saved me some hours of additional work on a new site of mine. Cheers.
Resources much like the one anyone reveal here are going to be very cooperative in my opinion! I will certainly post one of the links to this page on our blog. More than likely my guests will quickly realize that quite significant.
http://www.hermeshandbagoutlet.com
very thanks
You have very nice tutorial on site.
thanks for sharing ..
very thanks
Hi, great plugin! I finally managed to get it working with my custom theme but I’m having trouble with the archive page.
I display 8 posts by default, click on an archive month where I know there are more than 8 published posts but when I click “load more” I get the “no more posts to load” message on the button.
Any ideas why this could be happening?
Can anyone help me? I like the plugin but at this stage looks like I won’t be able to use it. Just doesn’t work in my archive.
Hi Kasia,
Did you get it to work?
Actually I was just thinking about doing something like this on my own blog. Then I just bump into your blog article accidentally. Speaking of fate…
Did you get it to work?
Is there anyway to make it work with a previous link instead of a next link?
Hi,
Thank you for this wonderful script, i got it working on my archives page, but not on the search page.
Also, i have a page template to display a blog. I have tried almost any possible solution but i cannot get the function to retrieve the value of $max.
When i look at the source code of the page, i can see “maxPages : 0 “.
I tried to force the value to 4 in the function, and then the button appeared.
My opinion is that it works with the default query (archives, category, etc) but not directly with custom loops.
Does anybody knows how to solve this ?
That would be really appreciated !
Rabih, can you tell me how you got it working on the archives page? Mine only shows the default number of posts and then says there are no more, when I know there are.
Works ok on the index page, though it doesn’t go back all the way to the beginning.
Hi Kasia, in my case it was pretty straight forward. By archives, i mean the default archive.php template. I added the markup inside the loop but after enwdhile.
In the php file for the plugin there is a condition : !is_singular(). Did you change it ?
If not, then you might be having the same issue as me in my custom page template : you altered the loop or created a different loop.
I have noticed that it only works for the main loop (check the codex, the main loop has some particularities).
Do the following : open the code source of the page and look close to the end : you should see something similar :
startPage: “1”,
maxPages: “4”,
nextLink: “http://localhost:8888/wordpress/2011/10/page/2/”
If you see maxPages : “0” then you are having a serious issue.
thanks for the response Rabih.
I haven’t changed anything in the plugin, should I?
Yes I was also taking about archive.php. If I look at the source code I get the correct value for maxPages (not 0) and nextLink, but it still doesn’t show the results ??
I did some more tests, and i am stuck at the same point.
When i click on the button, it says loading, then no more posts but meanwhile no posts load.
I will try to check deeper and i will get back to you as soon as i get something !
I did manage to get it to work in a page template by getting rid of the main if statements in the js file. But you have to play with it, and hard code a little. Not very elegant i suppose.
Hey I’m getting
“startPage”:”1″,”
maxPages”:null,”
nextLink”:”http:\/\/dev.touch-akl.com\/childsplay\/page\/2\/”
can anyone help?
Even though I think it can be implemented as a huge improvement for usability, I’m pretty sure it does not do good for SEO. Thanks for the tutorial though.
Doesn’t work for me. I changed the #content to my “content” of #body in the JS file. I’m also using this in a template that calls a custom post type. Could this be the issue?
This is my first opportunity to visit this website. I found some interesting things and I will apply to the development of my blog. Thanks for sharing useful information.
hope you will write more ,thanks a lot for your information.
I got it to work (locally), but there is one major problem. The plugin loads the same posts that currently showing.
Hi,
I am having exactly same issue impementing ajax load more.
Can any one please halp us?
Thanks,
Tejas
I know that this is a really old comment… But I was looking for this answer too.. so if anyone else has the same issue, it turned out it was because I was trying to show the first 12 posts.. using…” query_posts(‘showposts=12’); “.. I’m not sure how to get around that bit now.. but if you know the answer please feel free to let me know :)
Thanks for this plugin first off all. The best code out there as of yet.
However, I need a solution to continue load the Facebook like buttons for the newly loaded posts. It seems Facebook initially attaches these on page load, so they are not loaded per ajax request.
Is there anything I can do to force load the Facebook like buttons along each post as well?
It would be a deal breaker if I can not figure this out. I would really appreciate any insight.
Thanks
For the 1% chance someone is looking for this:
jQuery(document).ajaxComplete(function($){
try{
FB.XFBML.parse();
}catch(ex){}
});
Hi Marius,
that FB like code snippet is great as I’m trying to use this plugin but also have my social media buttons (FB like, retweet, and google+) be listed for each post excerpt as well.
Your code works for calling the FB like button, but I was wondering if you or anyone else might know how to call the twitter and Goole+ icons from the”tweet share like plugin: http://letusbuzz.com/tweet-share-like-plusone/
Thanks for sharing your improvement here Marius, nice work!
Hi Marius, did you fix that ShareThis error?
Very helpful and great article thank you.
It’s difficult to get knowledgeable people today on this subject, but you sound like you know what you are talking about. Thanks for this informative post.
It doesn’t work with the lazy-load plugin. (Images stay hidden.) Any idea how to solve it?
Sir
Log in to each day your blog I find very useful
Remain few and thanks to you
Greetings to you
Awesome plugin!
The only problem I can see with it is that if the user goes to a post, say, on page 3, then hits the back button, they will lose their place and be taken back to only “page 1”.
Is there a way to resolve this so they get taken back to where they left off?
Excellent Plugin, this has helped me a lot
Hi! this script it´s awesome, but… I can´make it work… the buttom appears and I can click it, but it just says: “can´t load more posts”… when i look at the HTML source code I can see this:
/* */
I think that is the problem, all those “\ /” in the link… how I can solve this? :S
sorry, code doesn´t appears here, but well, in the script over the HTML souce the next page URL appears like this:
http:\/\/dixel.accountsupport.com\/clientes\/multisite\/page\/2\/
instead:
http://dixel.accountsupport.com/clientes/multisite/page/2/
how I can solve this? or it´s normal?
this is very workfull. but i think you must add admin panel for change // Insert the “More Posts” link. so your application can compatible with other theme. Thanks you’re help me. :)
great post, thank u!
bvnbv vn vbv nvb nvbnbv vb
This is amazing but please let me know how to use it with custom post types!
I’d also like to know how to use this with Custom Post Types…
This is a suggestion on how to get it to work with Custom Post types – http://wordpress.stackexchange.com/questions/39141/load-next-wordpress-posts-with-ajax/39144#39144
Hi Rik,
Thanks, but Infinite Scroll doesn’t work yet with custom post types. I contacted the author, and he has been working on this, but so far with no success.
Thanks for the share. Im having trouble with AJAX as well
Hi all,
I see a lot of comments of people who are having trouble working it up with other jquery plugins.
What happens is that when the page loads, the jquery scripts do their homework and apply to the elements they are supposed to apply to.
When you load more posts, the jquery scripts can not apply to these posts because the page has already loaded.
What you can do is the following :
jQuery(‘.pagination a’).live(‘click’, function(e){
e.preventDefault();
jQuery(‘#loop-content’).html(”);
jQuery(‘#loop-content’).load(link+’ #loop-content’, function(){
jQuery(“img”).fancybox({ });
jQuery(“menu”).superfish({ });
});
});
I have written above a random code. The most important thing to understand is that when we click on .pagination a, we do the ajax loading (.html and .load) and then we bind a function that will contain all the jQuery necessary to the other plugins. In this case i showed fancybox but it could be anything else and multiple codes.
Another important thing is that you must write the code for the functions (fancybox, superfish, etc) twice : one as you used to do, and another one inside the ajax call.
I am sorry because i am not able to give a precise example with the Load More Posts, i have stopped working on it many months ago. But with the info above, you should be able make it work with other plugins.
Good luck everyone !
This is awesome! I’ve been implementing this as a plugin for my personal blog (custom theme). I ended up adding some jquery slide effects.
It’s a very simple and versatile piece of code!
You should really package it as a plugin!!
@Pedro
Could you share the plugin you’ve made with us?
Excellent tutorial, thanks.
I like this blog
Hello,
I am having real troubles with custom query. The pagination actually works correctly, but it seems like PBD cannot read the max number of pages.
I am also using it in the archives and categories pages and that works fine.
I’ve tried to modify $max = $wp_query->max_num_pages; to $max=$mycustomquery->max_num_pages; and to force the $max to display 4 pages and that works for that page but it will mess up the archive and categories pages.
Could anyone guide me in the correct direction?
THanks a lot!
Hi Michael,
Just a question do I upload the files into my theme, or put them as a plugin because for some reason it says when I upload the files as a plugin that only 1 is active.
I just start reading this important tutorial and I have a key question since i am a beginner in ajax.
Please, does the demo site, usees ajax after clicking on one of the recent post in the sidebar??? I see that the page doesnt relaod, even if the url changes in adress bar. please to explain me breively how to do this
Thanks in advance
how to implement the same on Custom Post Type ?
This is excellent, thank you. I have one problem that I can’t quite figure out. I’ve set this up on a blog with several posts per day so I am using a function that has a date header for every day and all the posts fall under that. For some reason, when I use this plugin it pulls in the posts but not the date header even though that page would normally have them. This is the function I am using to do this:
function intermittent_date_header( $d=”, $before=”, $after=”, $echo = true )
{
global $idh_last_date_header;
// Get the current date
$date_header = the_date( $d, $before, $after, false );
// If it’s the same, don’t bother continuing
if ( $date_header == $idh_last_date_header ) return;
// Record the current date header as the last one
$idh_last_date_header = $date_header;
// Decide what to do, and do it. Return, or echo…
if ( ! $echo ) return $date_header;
echo $date_header;
}
and I call the function in my loop.php file just before the div for the post.
Any thoughts on how I could fix this?
Thank you!
I posted too soon! Just figured it out. In case anyone else needs this kind of thing. Since I had my function directly before my posts I wrapped my function in a new div with a class of “post-content” and then changed the line in load-posts.php that loads the page to:
$(‘.pbd-alp-placeholder-‘+ pageNum).load(nextLink + ‘ .post-content’,
function() { …
so it would pull in the date header as well.
Just brilliant! After an entire afternoon looking for a simple ‘load more posts’ button plug-in for WordPress I finally found this and it worked right away. Thanks for taking the time to put this together.
Does this plugin have something connected with permalinks? i have tried to use it on my pc on localhost xampp server and i can’t make it work. When i activate it it loads and button is working, but when i click on load more posts it load only 1st time 5 more posts, every other time when i click it repeats loading same 5 posts from first load. I have disabled permalinks and i tested on few different themes, and different installations. Every time it’s same.
That started happening to me also hence why I’m back here to find out how to stop that happening. A little puzzled to say the least.
Ok i installed it on web server where i can browse website with domain name and where i can setup permalinks, and now script is working, apparently on websites where permalinks are disabled script wont work. This is not much problem because almost every website has permalinks enabled now. Now other problem that i run into it is every posts that are loaded with ajax, dont have other jquery functions. I have cufon font replace enabled on post titles, and first 5 posts that are loaded at start have fancy font titles enabled, other posts dont have cufon fonts and other scripts.
Now im answering to my own question but this may be helpful to someone else who stumble upon same problems :)
I found solution to load jquery functions on posts that are loaded with ajax. On page load wordpress loads jquery scripts at start. But specific functions are not loaded later on. To reload functions in posts that are loaded with ajax you just need to include them in load-posts.js file on line 39 after load function. And for example, to have loaded cufon and tiptip function i have altered my code like this
$(‘.pbd-alp-placeholder-‘+ pageNum).load(nextLink + ‘ .post’,
function() {
Cufon.refresh();
$(‘.portfoliotitle, .tip’).tipTip();
// Update page number and nextLink.
pageNum++;
nextLink = nextLink.replace(/\/page\/[0-9]?/, ‘/page/’+ pageNum);
// Add a new placeholder, for when user clicks again.
$(‘#pbd-alp-load-posts’)
.before(”)
// Update the button message.
if(pageNum <= max) {
$('#pbd-alp-load-posts a').text('Load More Posts');
} else {
$('#pbd-alp-load-posts a').text('No more posts to load.');
}
}
);
Hope this will be helpful to someone, thanks for awesome plugin.
I’m trying the same thing with a plugin which applies some animations to the posts, but it’s still not working on ajax content. If I do what you did I just get ‘is not defined’ which tells me it can’t access the plugin source.
Thanks for sharing! I’m currently trying to get Infinite Scroll to work along the same lines as this but if that fails I’ll give your suggestion a go.
I noticed someone else (Rabih?) had recommended a way round this problem somewhere else in the comments which might also be useful to people too.
I stumbled here looking for an option to another plugin called infinite-scroll ..with similar function..but sadly it doesnt work for post-types. Any chances of this being developed into a wordpress plugin any sooner.?
@Aleksandar THANKS! legend :)
Great tutorial! Just followed the instructions and it worked out perfect! Thank you for explaining everything step by step. This was my first pugin :)
Very good tutorial, thanks.
bookmarked ur site
http://www.davidsweightlossjournal.com/ tpgj
[url=http://www.antwerksstudio.com]monster beats[/url]
Hi Michael,
I am install your plugin but i don’t know how to use.I activate your plugin And load button is also visible in my website – http://www.develovers.in/test but i click on that button they show me “No more Post to Load”.
Please give me the Solution i am new in wordpress.
Thanks in Advance
Nitin Jain
hello ?
give me your contact information, and i will help you !…
You forgot the IE gradient :)
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=’#f7f6f2′, endColorstr=’#dfdbcc’); /*for IE*/
hello, I want to let the posts in Insert the Column ! how to do that ? please send my E-mail !
Keep on writing, great job!
I’m trying to set AJAX up in a specific new WP_Query block with no luck.
http://pastebin.com/nMQSQ3kZ
I have four other blocks querying posts in the same page template, so any AJAX script can’t do anything.
So agree, the explanations are very useful! Well done.
System is not working after loading page 10, loading of page 11 hangs and after clicking again is error message “no more post to load” displayed…
Johny,
Try changing the line with the regular expression, to the following:
nextLink = nextLink.replace(/\/page\/\d{0,9}/, ‘/page/’+ pageNum);
This will work where you have more than 10 pages.
You can see it in action in this test jsfiddle… http://jsfiddle.net/e7VQh/
It should also work no matter whether the url has a trailing slash or not.
it works, thank you
I have the same problem, but this fix doesnt work for me…
Any idea?!
Excellent plugin!
@Javier
Try replacing line 42 with:
http://pastebin.com/ia8pZYwD
Michael,
Thanks for the great post. Took a little while to get it working with my Custom Post Types and custom WP_Query(), but eventually got it sorted.
Cheers!
Hi Michael,
How did you get it to work with your custom post types? It does work with regular WP posts.
Hi Anthony,
How did you get it to work with your custom post types? It does work with regular WP posts.
This plugin doesn’t work at all, i mean literally it does not work
I installed the plugin clicked activate and nothing happens, it doesn’t show up at all, i checked the #content and .navigation it’s all right but this plugin doesn’t show up at all
Great plug-in, works pretty sweet!
Any way to add a counter wich displays the amount of posts left to load? Would be really interesting thing to add!
Great plugin. It works well with regular posts, but not with custom posts. :( Anybody know how to get this plugin to work with custom post types?
The following will point you in the right direction: add your custom post-type to $wp_query; by adding the following:
$args = array(
‘post_type’ => ‘post-type’
}
And: $query = new WP_Query($args); above $max = $wp_query->max_num_pages;
From there on you can pretty much customize it the way you like .. even integrate your theme options if you have them! (I renamed $wp_query to $query by the way, not sure if that is really necessary). Play around with it a little and you’ll be able to do all sorts of cool stuff!
Great plug-in!
“You’re a genius, Gump!” JK :) Thanks so much for your help, DJ! Worked perfect!
One thought… what if I want to add multiple post types?
Hi DJ and Adam,
How did you achieve it to get it working with custom post types?? I’ve tried what DJ said, but for me it isn’t working…
In which file do you need to edit this??
Thanks in advance!
Glad to see it helped.
For multiple post-types you could try something like: ‘post_type’ => ‘post-type, post-type’ or place them in an array like ‘post_type’ => array ( ‘post-type, post-type’).
Thanks, DJ! I haven’t had the chance to test just yet, but I’m sure it works!
This is the perfect plugin for what I need – but I just can’t get it to work.
The button appears and it seems to recognize that there are posts to load (Loading. . .) but doesn’t load the posts and eventually displays ‘No more posts to load’.
I know it’s something simple but just can’t locate the issue. I’m using multiple loops. Loop 1: query (query reset with wp_reset_query()) and Loop 2: main loop. I have used the correct class/id for the button and posts container.
Dev: http://www.simonevery.com/testing/hwc-development/
Happy to share my code if anyone reckons they can help!
Thanks in advance :-)
Hey,
I think im having the same problem.
– I have installed the plugin.
– Added id=”content” to the div that contains my loop.
– I have 2 loops. 1 uses wp_query and the other is the default loop
– The button is showing and on click makes a connection and appends:
If you press the button again it appends another: and so on.
Is there something im missing?
You can view my site at http://www.videohunnnt.com
If anyone can help it’d be great!
Thanks in advance!
Never mind, my problem was that i was’nt including the .post class in the li that wraps my blog post inside the loop.
Hey,
Yeah this turned out to be the problem I was having too.
Adding the class ‘post’ to my post div in the loop fixed everything.
Thanks!
I applaud you for taking the time to write detailed instructions that explains how things actually work. Kudos!
What about re-firing jquery functions after the AJAX page load .. like a flexslider of jplayer for example?
jQuery functions stop working after a page load…
I had this problem as i was using jquery for nth-child.
i just called my function after the following line:
.before(”)
Sorry, it wont let me past the code.. i called my function on line 47.
Hope that helps
woops.
Chris,
Could you paste your code in a jsfiddle? http://jsfiddle.net/
Would be apriciated! :-)
Chris,
I actually see what you mean now.
But what about jquery (jplayer for example) that is used inline and unique to a post. Can’t call it one time like you could with a lightbox for example!
Hi, could you tell me how you figured it out? I’m using lightbox (actually view.js) and as soon as i load more posts it stops working. any ideas?
Ale,
Wrap it inside a function:
function function_name() {
}
and call it like function(); after you’ve initiated your page load.
Someone have any idea on how to do this with embedded JS like with jplayer for example?
Has anyone got this working with Masonry?
It loads the posts in the container I applied masonry to, but no matter what I try the new posts just won’t have it…
How to include this in index.php?
i have no idea about that? please can you explain me in short ways, i know about #content but i have no idea what else to include…
Please any help ?
This is probably something I’m overlooking, but I’m not seeing a solution.
My default posts per page is eight. I have a gallery page which loads 16 posts because the thumbnail don’t take up as much room.
On the gallery page instead of getting the next 16 posts, the posts are duplicated.
Similar thing happens with two loops on a page.
Has anyone run into this problem and found a solution?
Thanks
Hi! you already find a solution for index page?
The problem lies with the new pagination system of WordPress 3.1+. Replace line 42 in the Javascript file with the text pasted below and you should be fine.
http://pastebin.com/ia8pZYwD
How to include this
Hi ,
Please can anyone explain how to use this code ?
I activated the plugin , But how can i call or use it in my codebase ?
Thanks in advance :)
Thanks a lot man. You save me a lot of time. Great Job!!!
Hi to all, how is everything, I think every one is getting more from this website, and your views are
nice designed for new people.
Hi there,
Thanks for this quick tutorial !
Everything works fine except that $max = $wp_query->max_num_pages; return 0 even tough I have 4 pages…
I hard coded maxPages and it works like a charm.
Any idea on why max_num_pages return 0 ?
Cheers,
J.
I have a very same problem. It seems, that global $wp_query has a hard time to make it to functions.php.
When I was starting to be nuts about that, I even called another query with same parameters (!!!) in functions.php, so the wp_localize_script function could get the parameters from it. But that’s obviously not the best approach …
So any suggestion for us, coders who want to use the plugin for custom wp_query?
Great plugin!
I use the following plugin with masorny, and I tampered with your code, so that posts load automatically when you scroll at the bottom of the page.
I removed the “” link from the #pbd-alp-load-posts paragraph, since I don’t want visitors to click it anymore.
Also note that my container’s id is #container.
Change the javascript with the code below:
jQuery(document).ready(function($) {
var pageNum = parseInt(pbd_alp.startPage) + 1;
var max = parseInt(pbd_alp.maxPages);
var nextLink = pbd_alp.nextLink;
if(pageNum <= max) {
$('#container')
.append('’)
.append(‘Loading more posts…’);
}
// autoLoadPosts
function autoLoadPosts(){
if(pageNum <= max) {
$(this).text('Loading posts…');
$('.pbd-alp-placeholder-'+ pageNum).load(nextLink + ' .post',
function() { $('#container').masonry('reload');
pageNum++;
nextLink = nextLink.replace(/\/page\/[0-9]?/, '/page/'+ pageNum);
$('#pbd-alp-load-posts')
.before('’)
if(pageNum <= max) {
} else {
$('#pbd-alp-load-posts').text('No more posts to load.');
}
}
);
} else {
$('#pbd-alp-load-posts').append('.');
}
return false;
};
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
autoLoadPosts();
};
});
});
You can see a live version here: http://viewz.gr/
I see it works on your site, but it didn’t worked for me. I added your code, changed some classes and added latest masonry plugin, but no result, maybe I missed some parts?
What else should be added?
What is the problem? It does not load the new posts? This is my updated code for load-post-auto.js, hope it works for you too:
jQuery(document).ready(function($) {
var pageNum = parseInt(pbd_alp.startPage);
var max = parseInt(pbd_alp.maxPages);
var nextLink = pbd_alp.nextLink; pageNum++;
if(pageNum <= max) {
$('#container')
.append('')
.append('Scroll down to load more');
}
// autoLoadPosts
function autoLoadPosts(){ $('#container').masonry('reload');
if(pageNum <= max) {
$('#pbd-alp-load-posts').text('Loading more posts...');
$('.pbd-alp-placeholder-'+ pageNum)
.load(nextLink + ' .post', function() { $('#container').masonry('reload'); pageNum++; nextLink = nextLink.replace(//page/[0-9]*/, '/page/'+ pageNum);
$('#pbd-alp-load-posts')
.before('');
if(pageNum <= max) { $('#pbd-alp-load-posts').text('Scroll down to load more'); } else { $('#pbd-alp-load-posts').text('No more posts to load.'); }
});
} else { $('#pbd-alp-load-posts').append('.'); }
return false;
};
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
autoLoadPosts(); $('#container').masonry('reload');
};
});
});
P.S.: if the plugin load the next posts, but they end up ovelapping older posts, make sure to give a height to the images so that the plugin measures the masorny-block height properly.
AJAX is such a strong language, Thanks for sharing it with us
Great plugin, however I’m having a problem. I’m building a gallery style blog, each post is basically a huge featured image and then just the date underneath.
When I click ‘load more posts’ the featured images in the next set of posts don’t show up. Any idea why?
Thanks
Hi Tom,
It is probably because you didn’t change the javascript according to your page template ! In this cas the line search for the function .load() and change the parameters .post by the selector that you want to load from your template…
Imagine you have something like this :
15th october 2012
You will load .myImage !
Does it make sense ?
Thanks Jacques, yes you’re right because I just installed infinite scroll and the same thing happened. They actually have the option to select the selector in the wordpress admin area though so after a few guesses at which div it was I got the right one and it works perfectly! :)
I’ll make a mental note the next time I need to use the feature and try this plugin instead
Tom
Glad it helps you ! This plugin is an amazing piece of code and needs sometimes a little modification to work properly. That’s why the author made a tutorial out of it…
Cheers mate.
Jacques.
It seems that the plugin loads up to 100 posts and then stops. I know that because I currently have 102 posts in my blog. I tried increasing the “posts per page” at my dashboard to 11, instead of 10, and now it worked fine – showing all 102 posts.
Next, I tried creating a few posts, so that my posts add up to 111, to check if the 111st will show up. (10 pages * 11 posts per page = 110)
Unfortunatelly, the 111st post does not load!
So, the plugin loads up to 10 pages of posts, and fails to load the rest.
Is it a WordPress thing, can we bypass it somehow to load infinite “pages” of posts?
Anyone?
OK, found it, already posted above.
Thanx to the comment by 406 media:
nextLink.replace(/\/page\/[0-9]?/, ‘/page/’+ pageNum);
is replaced with:
nextLink.replace(/\/page\/[0-9]*/, ‘/page/’+ pageNum);
and it works just fine!
You have very nice tutorial on site.
thanks for sharing ..
hi,
where can i found simple instruction? can’t understand this post! :(
Hi. Worked great thanks for sharing.
Can you help me a hint on how to make new posts fade in? Whatever I try doesn’t seem to work.
Thanks
Got it, by adding
$( this ).hide().fadeIn(500);
INSIDE the load function. Thanks I’ve learnt a lot from this.
Cheers!
Thanks Jacques, yes you’re right because I just installed infinite scroll and the same thing happened
Someone there can help me?
I’m trying to use it in my theme, and I starter trying and that doesn`t work… So I made a new site using the Tewnty Eleven theme. Okay, works well. So I tried to see the diferences between the cases, and I made some changes in the Twenty Eleven theme, I tought that was some different configuration to do, okay, I changed and make it wors with a similar structure of my theme. It wored well. But when I changed the conditional (!is_singular()) to a specific one (is_page(‘mypagename’)) it doesn’t work… in either of the themes, I tough I changed something wrong but in the Twenty Eleven when I put the conditional !is_singular it works in the index page, but not in the page that i wanted it to work… Please someome help me… TKS
Well, I didn’t saw that the plugin was duplicating the posts, I can see now that the problem is when I custom the query… It doesn’t work… someome can help me???
PLEASEEEEE!
Great solution! Thanks!!
you already find a solution for index page? Great plugin , In love with it !
Very nice plugin!
I would also add I18N capabilities (I had to modify the code in order to translate it to Spanish), congrats!
Must Admit Very nice plugin! I’m having a problem though and wonder if anyone can advise on how to fix it.
When loading new posts the thumbnails from NGG (NextGen Gallery) do not open the larger images in the lightbox…
Please if there is any advise on how to fix this i’d appreciate it.. I assume it’s due to the AJAX loading the pages and there not being a page refresh?
Very good work here! Is there any way to integrate that with the “Read More” button for the #more functionality so you can load the whole post from the main page without having to click into the whole post?
Just wondering, keep up the good work!
Absolutely, you could definitely do that using almost the same technique. The jQuery in this post picks out the part of the next page to load in by looking for a particular div. If you tweak those div references to point to the content of your post, then that’s what it will look for. After that, you just make sure that it overwrites the right post content section on the main page.
The exact CSS classes to use for that will vary depending on your theme, but the overall approach is unchanged.
Can anyone confirm that this works with WordPress 3.5? Thanks a lot.
Excellent tutorial, thank you! I particularly love the fact that you can pass data around from php to javascript with wp_localize_script(). Great function. Great usage with loading posts via AJAX.
This is exactly what I was looking for, but I can’t seem to figure out how to get the Load More Posts link to show up somewhere else. Right now, it’s showing up right above the Footer, but I want it to be under my posts. How can I manually add this function to my theme?
It seems like it cannot find the page even though the permalink is set to the default of what the wordpress next posts button is.
Is my way of ajax not very good for wordpress? I have seen people use other ways but I dont quite understand them.
Hi, thanks for an excellent plugin. Very easy to implement and customize.
I was wondering though, if any of you have got an idea how to get the plugin to work on a site with two different loops going on at the same time. Both loops are based on category-queries, so that one loop only shows posts from one category, and the other loops from another category.
Any good ideas? Thank you!
I got the same problem. I have a modified version of WP and I don’t understand which code I should to put on my PHP files to get it work.
any help? thanks!
Hey guys i’m currently using your plugin which works very well on my site. However, when I click load more post things like “Disqus Comment Counts and AddThis buttons will not load”. They only load once but once on page load.