Infinite Scroll is a popular way to dynamically load fresh content into a site as a user scrolls down through it. It’s also quite easy to code into a WordPress theme. Here’s a quick walkthrough of how to do it:
(If you’re looking for a plugin to do this instead, use the “Infinite Scroll” module in the Jetpack plugin).
Get the Script Assets
Download a copy of “jquery.infinitescroll.min.js” from the GitHub repository, and drop it into the “scripts” or “js” folder of your WordPress theme.
Pick out the ajax-loader.gif of your choice, and add it to your theme “images” folder.
Enqueue the Script
You’ll need to register and enqueue the required script in functions.php:
[gist id=”399e8c6966360dbac708ffff4178b780″ file=”enqueue.php” lines=”2-18″]
Init the Script
In the code snippet below I list the parameters I used in my theme. You’ll likely need to customize these in order to match your theme markup:
- img: The path to the ajax loader image
- nextSelector: Selector for the “previous posts” link.
- navSelector: Containing selector for the previous/next navigation links.
- itemSelector: Selector for posts. This might be .hentry, .post, .etc
- contentSelector: Containing div for your posts.
[gist id=”399e8c6966360dbac708ffff4178b780″ file=”enqueue.php” lines=”20-42″]
Note: Also make sure to update “custom” to your own textdomain for translations.
Try it out
If you load a category or home page the site should now be infinite scrolling. If not, check the web developer console to see if a script didn’t load or if there’s a javascript error. Also, double check that you’re selectors listed above are all correct.
Possible Issues
If you’re releasing a theme for other people to use, definitely include an option to turn off infinite scroll. It won’t work for everyone- especially if they have plugins that add social buttons or render additional javascript in the post content.
I wrote a little more about some of those issues in this post
Thanks for this neat piece of code. I’ve always included scripts on my footer and header manually – by not using wp_enqueue. Now I know the right way to do it.
how to add one more “contentSelector”:”#content” ?
Not sure I understand what you’re trying to do.
I mean
“contentSelector”:”one”,”two”
how can I add the “two”
It doesn’t really work like that. You can only have one selector. Doesn’t one div contain all your posts? If not, use a really general selector like “body”. You can read more about how the ajax request works here: http://api.jquery.com/load/
I have simple question…
at this tutorial, the code will automatically load content when the browser reach the bottom of page…
But how can I add “Load More” button? so, it’ll load the content only if visitor hit the “Load More” button.
thanks anyway.
I’ve the same problem, I don’t find the solution ? Any ideas ?
Thanks for this great tutorial !! :)
F²
Thanks Devin, just one thing, on the 404 fix your function name on the hook is wrong ;) Thanks though it worked beautifully.
Thanks. Copy/paste error. Fixed now.
Thanks for the excellent tutorial! I really like this your clean solution and much prefer it over installing yet another plugin ;)
I do have one question though; I would like to get this to work on a horizontal scrolling div, would you know how I can do that?
No, you’d have to change where the “end of page” detection fires from vertical to horizontal. I’d just dig into the infinite scroll script and hack on it.
I finally managed to get this to work. For anyone interested; I’ve posted my solution on GitHub https://github.com/paulirish/infinite-scroll/issues/151#issuecomment-5268510
Great! Thanks for reporting back.
Hi, thanks for the great tutorial! It helped me to get Infinite Scroll partially working on my site. I’m using the Shaken Grid WP theme which requires manual jQuery install of Infinite Scroll instead of the WP plugin, probably since it uses Isotope to arrange page elements.
With your post’s help, I’ve gotten far enough that the next page’s content loads, but it doesn’t sort. It just overlaps in a jumble with the original content.
One big thing I’m confused about is that I don’t know where I’m supposed to put callbacks and such. In the Shaken Grid documentation, it says to add the following script to do the sort:
jQuery('.sort').isotope( 'appended', jQuery( arguments[0] ));
I’m assuming that goes in the function.php, in place of the code you have:
jQuery( infinite_scroll.contentSelector ).infinitescroll( infinite_scroll );
But I can’t get them to work whatsoever. I think I’m missing something obvious.
Any suggestions? Thanks!
Well, not ten minutes after posting that I realized my mistake. That isotope call would need to go where the theme runs the isotope sort script, which was in script.js. Derp.
Got it added but now I’m having trouble adding Fancybox callbacks to work after the Infinite Scroll appends. We’ll see if I can solve that one myself :)
Hi Jesse,
I’m having the exact same issue. To get this straight, the call in the scripts.js file should be like this right:
jQuery('.sort').isotope('appended', jQuery( arguments[0] ) {
itemSelector : '.box:not(.invis)',
transformsEnabled: false,
masonry: {
columnWidth : 175
},
onLayout: function(){
centerLayout();
}
});
Is there any way to maintain the filtering functions of isotope when new content is added with infiniteScroll? Because right now the filtering gets disabled as soon as the next content is loaded….
Thanks!
I think I found a solution to get infinite Scroll with combination filtering working with the Shaken Grid theme!
In functions.php I placed this piece of code to initialize infinite Scroll:
Mind the 50 in the add_action call to load the script AFTER jquery.infinitescroll.min.js is loaded in the footer.
In the script.js file keep the original piece of script that runs the isotope but remove the transformsEnabled: false line to get it working in Opera browser:
I tested in the following browsers:
MacOs: Firefox 13.0.1, Safari 5.1.7, Chrome 19.0.1084.54, Opera 12
Windows: IE7, IE8, Firefox 8.0.1, Safari 5.1, Chrome 19.0.1084.56, Opera 12
When new content gets inserted by infinite Scroll, the filtering still works and WILL filter the new content :)
Hope this helps anyone!
Hi Jesse, this is a desperate message to ask you if you achieve make infinite scroll works on Shaken Grid, since years ago I´m looking for a solution but I never found one.
Thanks in advance for the info.
Oswaldo.
Can you tell me where exactly should i put this the second part of code?
I already put those infinite scroll in my home.php and archive/category.php, but it didn’t works…, any solution..? i already put the first part which contain “Load javascripts used by the theme” in my function.php. Need your advice, thanks.
max
It all goes in functions.php.
Hello,
Could you help me with the selectors for the autofocus+ theme? I leave the link of site in the website field.
Thanks!
Sorry, can’t offer specific theme customization help here. Try posting in the WordPress forums.
Thanks for this post Devin! It was a lot of help when trying to implement this into a WordPress comments section. You can check it out here: http://causehealth.org
I am having trouble with the code. When I refresh the page and scroll I can see the “older posts” link until I hit the bottom of the page, then that link disappears and that’s it.
I did not change “custom” because I am not quite sure what the “textdomain” is suppose to be. Could you give an example or explain it further, I am extremely new to WordPress.
I am also using isotope.js
Any and all help would be greatly appreciated. Thank You!
Thanx for sharing. It works perfectly.
Hello,
I have been trying to add the in infinite scroll to my site and it doesn’t work. The plugin doesn’t wanna work so I thought I’d try it this way. The problem I am having is that I am new to this, so I don’t know exactly how to do it. The instructions are fairly clear, I am able to get to my functions.php file, but I don’t know where in that file I have to paste these lines. I tried at several places and I didn’t get it right.
Can someone please help me out and give me a step by step detailed walk through on where and how to get these done?
Any help is greatly appreciated. I really want to get this to work.
Thanks!
If in doubt, put it at the very bottom of your functions.php- after everything else.
Some things to check:
Make sure the script is being enqueued on the front end of your theme (view the source, look for the script)
Make sure you have the selectors for prev/next correct
Hi Devin, Thank you for the great tutorial,
Just one question, how does this work with scroll to top?
I mean would it go to the top of page 1 or the top of the current page loaded via ajax?
Thanks for all the time you dedicate helping people and releasing great stuff!!!
Antonio
Depends how you set up Scroll to Top, but I would assume the top of the browser window.
Works great, thanks you Devin ;)
Thanks for the information. Should this work with Portfolio Press?
I’m working in a child theme to Portfolio Press but altering functions.php just breaks the server connection.
The .js and .gif files: do the have to be placed in the child theme, or can they be in the parent’s directory?
Also, these selectors you mention (newbie alert), would I be looking in the style.CSS for them?
Finally, I wonder if it’s also possible, theoretically, to have the menu nav stick to the top of the screen? Not trying to be funny, I’m too new to these dev issues to know if I’m being outrageous, but it seems to make sense from a UX standpoint; like in one pagers.
Thanks
Gregg
Hi Gregg. Yes, this would work with Portfolio Press. I built a paid version of that theme with Infinite Scroll built in if you just want to use that: https://wptheming.com/portfolio-plus/
.js and .gif files would go in the child theme if you want the parent theme to update without losing the changes.
I’d use the Chrome developer tools or Firebug to locate the selectors. Here’s a video about how to do that:
https://wptheming.com/2012/07/chrome-developer-tools-wordpress/
It is possible. Do some CSS research on position:absolute.
OK, thank you for the information.
Nice to know that you’ve created a premium version with some of these customizations.
Hello I have only one problem, I dont find the selector, now I put this:
“nextSelector”:”.alignleft”,
“navSelector”:”.pagination clearfix”,
“itemSelector”:”.entry post clearfix”,
“contentSelector”:”#et_pt_blog”
You or other can help me to find the correct selector, please? My site is in signature.
Sorry for my english but I’m italian.
Thanks a lot.
PS: I insert the tree part of code in function.php in ecc, is correct?
PSS: when I resolved that, I write an article on my site and I link this resource.
Try using the developer tools to figure out which selectors to use:
https://wptheming.com/2012/07/chrome-developer-tools-wordpress/
Hi Devin,
thanks for your answer and I used Firebug, similar tool for this task, but I dont understand if I must to put div.classselector or only .classselector for the div whit class=, and for the div whit id= I must insert it whit #idselector, is it correct?
Thanks.
I can’t offer customized support on this site. You might try posting your question on stackexchange or a forum like that.
Hi Devin,
I followed all the steps, but my website shows this message;
Warning: call_user_func_array() [function.call-user-func-array]: First argument is expected to be a valid callback, ‘custom_theme_js’ was given in /hermes/bosweb/web249/b2497/ipg.paraboladesignstud1/wp-includes/plugin.php on line 405
The line 405 in plugin.php is this;
call_user_func_array($the_[‘function’], array_slice($args, 0, (int) $the_[‘accepted_args’]));
How could I fix this?
Thank you,
Jaeeun
Looks like you didn’t put in a valid callback. Do you have custom_theme_js defined in your theme?
Hi Devin,
I have one question.
How to make plugin from your code?
Thank you
There’s already a couple out there. You might try this one: https://github.com/zslabs/wp-infinite-scroll
Works great, thanks.
Hello Devin.
I am trying to get this to work on my excerpts on my category page.
It seems there are many ways to call the navigation into the category.php, which one is the correct one to work with this tutorial. Thank you :)
Anyway you like. Just make sure the selectors in custom_infinite_scroll_js match the ones you use in the navigation.
Interesting…I followed this tutorial to a T, but I get no behavior at all and no errors either. I also tried manually embedding the script through the footer.php, same thing…its like it doesn’t exist…no errors again. Any idea? I’m sure its something simple…
Corrected.
Hello
i followed your tutorial
and infinite scroll is working properly
——
but how do i call back java-script
within your code
jQuery( infinite_scroll.contentSelector ).infinitescroll( infinite_scroll, callbackfunction );
Is this the correct way to callback a function
var sticky = $('.container').stickem();
sticky.destroy();
jQuery( infinite_scroll.contentSelector ).infinitescroll( infinite_scroll, callbackfunction );
Hi there,
do you know the way to make it work nicely with the back button?
say when i click to another page and then click back button it should show the same all posts it was showing…
hope you can help, it would be really useful! thanks!
Hi There,
This is like totally driving me crazy.
At first I did not see the script being loaded. So I changed this like of code:
if( ! is_singular() )
changed it toif( is_singular() )
Now the craze .js was loading, I can see it in firebug.
But the functionality still is not working … grrrrrr.
I am quite sure that I have the correct selectors, I mean, how hard can that be ?? :)
Is there a way to use firebug (or what other tool) to see whether or not the infinite scroll is trying to do something? Like, is there a way to see if the script is triggered yes or no ?
Any help is really appreciated!
Thanks,
Sander Baks (The Netherlands)
Sure, throw a console.log(‘Function fired’) in the js function you want to check.
Hi Devin, thank you very much for this great tutorial.
I have been facing issues though trying to load the jquery.infinitescroll.min.js file to my theme. I made several checks on the path, and everything seems fine, I also tested with ! is_singular() or is_singular() (without the !) also tried with is_tax() since I’m applying the scroll to the taxonomies listing.
So of course I’m getting the uncaught
TypeError: Object[object Object] has no method 'infinitescroll';
and I’m almost sure it’s because the .js file isn’t loading.The only way I could put this to work is by installing the infinitescroll plugin for WP which is actually loading the script.
Any thoughts on what could be my problem?
Thanks a lot in advance and sorry for the noob question.
You should be able to see if the file is loading by looking in your “Network” tab. Not sure how to help you debug that other than checking that everything was pasted correctly, and there’s no 404s in your Network tab, and that’s there’s no other script errors in your console log.
Hi again Devin, I’m using NextGen Gallery and would like to use this infinite scroll with it. So how is the markup then ?
Hi Devin
Followed your tutorial and it worked perfectly, thank you! One small problem. The javascript seems to refuse to load any additional scripts located within the posts. The two scripts I use are a Zippyshare embed code, and a Facebook comments code.
Help would be much appreciated it!
You’ll likely need to use a callback to re-init those scripts after the ajax load.
Hi Devin
Could you please help me find what those callbacks would be?
Chris
No, sorry, I don’t have time available to do custom development work. You could try posting in the WordPress forums, Stackexchange, or try hiring a developer to help you out.
Does this work with Isotope Masonry? If it is supposed to, I can’t seem to get the Isotope Masonry to work.
Yes, but it would need a callback. I believe @desando covers that in the Isotope docs.
I am using Infinite Scroll in a WordPress theme. I was having a problem where sticky posts were doubling when I scrolled down. The post would stay stuck to the top of the page as the others scrolled under them. Not aesthetically pleasing…
So I created a callback function to remove the sticky class like so:
var callbackfunction = jQuery('article').removeClass('sticky');
jQuery( infinite_scroll.contentSelector ).infinitescroll( infinite_scroll, callbackfunction );
All problems appeared to be solved. As in, the sticky posts still show up first, but don’t do the bad doubling thing when I scroll. But the console gives me theses errors:
Uncaught TypeError: Object [object Object] has no method ‘call’ jquery.infinitescroll.min.js:1
G.callback jquery.infinitescroll.min.js:1
c jquery.infinitescroll.min.js:1
H jquery.infinitescroll.min.js:1
v.extend.each jquery.infinitescroll.min.js:1
v.fn.v.each jquery.js:2
v.ajax.complete jquery.js:2
l jquery.js:2
c.fireWith jquery.js:2
T jquery.js:2
r jquery.js:2
Does this mean I’m using the callback function incorrectly?
It sounds like more of a pagination problem. When Infinite Scroll is off is the sticky attached to the top of page2? Because it shouldn’t be.
No, it was only happening with infinite scroll turned on.
I actually solved the problem by adding a short script before infinite scroll to remove the sticky class, like this:
jQuery(document).ready(function($) {
//if there is a sticky post remove sticky class
if ($('.sticky').length) {
$('.post').removeClass('sticky');
}
});
Hello! I would like to try this code, but I don’t know where should I put the initialization code – you can see it here below:
/**
* Infinite Scroll
*/
function custom_infinite_scroll_js() {
if( ! is_singular() ) { ?>
(…)
add_action( ‘wp_footer’, ‘custom_infinite_scroll_js’,100 );
– this is the initialization code, where should I put it? Into functions.php or into the file of the infinite-scroll plugin or in some external JS file, like main.js?
Sorry, for such a probably simple question, your help will be much appreciated!
It’s PHP. Should go in functions.php.
Will this code work on a category page/many different category pages on one website?
I am wondering what would be the difference between using the code that is provided here and activating Jetpack Infinite Scroll module. I am looking for a code that will work on different category pages. I am making a website for a graphic designer who has many different categories of his work and want to have infinite scroll feature.
It works on all archive pages, including categories. The Jetpack script works a bit different, but does generally the same thing.
Hello how do you add this on custom pages created? not only on archives.
You’d need to change “if( ! is_singular() ) {” to also include your page.
I asked some questions above, but I want to say that I got it all solved :) The code works like a charm. Great! It works perfect on a category page. If anyone has some issues he/she should make sure that the category template is named in a simple “category-id.php” manner and that the template make uses of the most basic wordpress loop, not new WP query or query_posts.
By the way I recommend a lot this great lecture on WP loops(it says for example that one should avoid using query_posts):
http://wordpress.tv/2012/06/15/andrew-nacin-wp_query/
Dude. Really thank you so much. it worked like a charm. I tried to use original wordpress plugin but didnt make it worked. Many thanks from Turkey.
when iam using jetpack infinity scroll, after 7 posts it is scrolling ( at the time of scrolling it is creating a new page) when we check that page with broken link checker tools it is creating a broken link.
how to solve this problem
Fix the broken link?
I am using infinite scroll on one of my websites, on a custom post type page in wordpress. The page calls posts into the page, and I have managed to get the pagination to work. (with a custom query) – The problem I have is that the infinity script does not stop at the end of the posts loaded into the page. My query use $loop instead of $wp-query and I think it has to do with the fix part using $wp-query… How can I stop the loop at the end of the posts… can I unhook the Jquery by if ($total_pages == 0) { Stop the infinite loop } and what would I need to place in {Stop the infinite loop} to make it work
As long as your standard paging works correctly, infinite scroll show work too. You can look at my theme Portfolio Press if you’re curious how I did it: https://github.com/devinsays/portfolio-press. Portfolio+ had infinite scroll built in: https://wptheming.com/portfolio-plus/
Have a way for i run a script after each post loaded??? The callback only run after all post loaded.
Onother quest is why internal scripts of the post don’t work in the loaded posts???
Hi agin.
Have any way for change the action context. I want create a button that activate the scroll instead of the reader go to bottom area of the site.
Hi Davin , thanks for the great info. How can I get it to work on multiple loops in a single page. For example I have 3 columns and they contain posts from 3 different categories. When user scrolls down it should fetch subsequent posts from respective categories and show them accordingly, more like mashable .com.
Many thanks.
Hey, I did this but it is not working with my theme, I have the number pagination, but when I activate the plugin and add the correct selectors (I guess) nothing happens.
Can you help me?
Probably won’t work with numbered pagination. Disable than and just use the prev/next page links.
Hello Devin
When I add this code in functions.php in my theme, So showing me error..
Parse error: syntax error, unexpected ‘}’ in /home4/jenocide/public_html/bustmybankaccount.com/wp-content/themes/covertstorebuilder/functions.php on line 1419
I want to use Infinite Scroll plugin, Actually I am newbie in wordpress, So Please can you help me.
I shall be very grateful to you
I waiting your response!!
Thanks
Rohit
Hello Devin
I am newbie on odesk, how to put code infinite scroll in my website,I was read your article, can you understand me step by step.
Thanks
Hi. Can anyone specify the selectors for twentyeleven theme?
[…] I hope the above work out for you and if you still feel any issues then check the original link that helped me a lot. Source […]
Hey buddy,
So I just tried this after having no luck with the WordPress IS plugins. I am using custom queries is that why this woudn’t be working for me?
As long as your previous/next buttons pull the right archives, it should work.
is it possible to implement this on a “split”page via tags ?
i think the problem lies in wp_link_pages that outputs
pages
<a=href"http://yoursite.com/your-page/2 <–page-number
i used this to remove the word pages wrapped in paragraphs but i still cant make it to work.
maybe it has something to do with the url? Because category/archives pages outputs something like http://yoursite.com/your-category/page/2
any help will be appreciated. Thanks
Why would you want to do that? If you have heavy assets or images, post loading them would be a better route.
Hi @Devin,
At first, let me thanks for the great article. But I’m facing issues with this:
I’m trying to add infinite scroll on my custom post type’s category page here:
http://v2.wp1189343.server-he.de/portfolio-category/material/
But, not working. Maybe I’m missing something. Please let me know.
Or can you tell me about these point on my website so I can directly put it down:
“nextSelector”:”#nav-below .nav-previous a”,
“navSelector”:”#nav-below”,
“itemSelector”:”article”,
“contentSelector”:”#content”
Thanks again.
You don’t have previous/next selectors.
Hi,
I am tried to edit my theme code, and unable to get this workout, is there any plugins for this?
thanks,
Yes, you can use the Infinite Scroll module in the Jetpack plugin (https://wordpress.org/plugins/jetpack/).
When I scroll down and the next page content is loaded, I always get sticky post. For every page load after scrolling down to the page, there is always the sticky post. But i need sticky post for the first time only when infinite scroll is not revoked yet. How can i do this? any help?
Found that your article is very useful. On top of that, I am looking for a way to insert ads post with infinitescroll. I believe I might need to modify the js query but not sure where is it