You are on page 1of 38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

Loading WordPress Posts Dynamically With AJAX


Daniel Pataki
January 21, 2015
#DEVELOPERS

#PHP

JAX has become all the rage in the past couple of years and for good
reason. AJAX (Asynchronous JavaScript and XML) is a way to have a

conversation with the server and display the results without reloading the
page.

This technique allows us to refresh Like counters, add items toa shoppingcart,
create dynamic forms and much more all without reloading the page.
In this post, Ill show you how toloadposts in place with AJAX using the Twenty
Fifteen default theme as our base.
Well look at why AJAX is used and, starting with a simple example, building AJAX
loading functionality into Twenty Fifteen.
Note: If you run into any issues trying to set up AJAX on your site,we can help! Our support
team is available 24/7 to help you with any WordPress issue (not just questions about our own
plugins!), so whether youre having problems with AJAX or want some advice on how to do
CSS tweaks, get in touch!

https://premium.wpmudev.org/blog/loadpostsajax/

1/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

Why Use AJAX?


When WordPress loads the rst page of posts on a WordPress site, it requests them
from the database and usesa loop todisplay them using the markup weve added.
Aside from this, navigation menus, widgets, graphics and other media, javascript
les, stylesheets and a bunch of other things are loaded.

Note that 72 requests are made on each page load.

As you can see in the image above (taken from Chrome Developer Tools), a fair
numberof assets are loaded. There is room for optimization here and some assets
like scripts will be cached, but even then it is a lot.
When page two of our posts is loaded it all happens again. WordPress retrieves the
posts and displays them using our markup. It also loads all the outlying elements of
the page all over again. In many cases (but not all) this is a waste of bandwidth and
detrimental to user experience. After all, no one likes waiting around for pages to
load.

Getting Started: Creating a Child Theme


https://premium.wpmudev.org/blog/loadpostsajax/

2/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

Before we modify Twenty Fifteen we shouldcreate a child theme. This ensures we


can continue updating the theme without losing our changes. You can read all about
how to do in in out guide How to Create a WordPress Child Theme.

Hello AJAX!
Lets begin with a simple example that demonstrates how AJAX Works. Well target
the links inside the pagination strip at the bottom of the page so that when you click
on a page number it will dynamically load that page using AJAX. When a pagination
link is clicked we will send a request to the server and alert the result.

Well be targeting the number links inside the pagination section.

Enqueuing Our Javascript


Our rst port of call is creating the JavaScript le and enqueueing it via our
themesfunctions.php le.
I created a

js

folder and a

ajaxpagination.js

le in it. Once you have done the same,

open your functions le and add the script to the already existing

theme_enqueue_assets()

function:

functionmy_enqueue_assets(){

wp_enqueue_style('parentstyle',get_template_directory_uri().'/style.css');

wp_enqueue_script('ajaxpagination',get_stylesheet_directory_uri().'/js/ajaxpagination.js',array('

enqueue.phphostedwith

byGitHub

viewraw

If youre confused about enqueuing read our article on adding scripts and styles to
https://premium.wpmudev.org/blog/loadpostsajax/

3/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

WordPress the right way. In a nutshell, weve told WordPress what wed like to call
our script (parameter one), where it is located (parameter two), what the prerequisites are (parameter three), the version number (parameter four) and that wed
like to load it in the footer (parameter ve).
Note that when enqueueing the stylesheet I used

get_template_directory_uri()

. This

function always points to the directory of the parent theme. When enqueueing our
script I used

get_stylesheet_directory_uri()

. This points to the child themes directory if

used within a child theme.


Since were loading the script in the footer you can paste
into

ajaxpagination.js

alert('ScriptIsEnqueued')

and reload the page to check if it works. If it does, the text

should be alerted properly.

Creating an Event
The next task is to create an event which will trigger an AJAX call. In our case the
event is the clicking of a specic link. To target the link well need to nd out a bit
about the element classes and IDs around it.

The source code for the pagination from Chrome Dev Tools.

In case youre wondering how I got this to show up, I pressed Shift+Command+C on
my Mac (Shift+Control+C on Windows), hovered over the element I wanted to
https://premium.wpmudev.org/blog/loadpostsajax/

4/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

inspect and clicked it.


This tells me that our pagination links have the class
has the class of
navlinks

next

and these are all contained in a

pagenumbers
nav

, the next link also

element with the class of

. Not shown here is the previous link, which has the class of

to the regular

pagenumbers

prev

in addition

class.

For the time being, lets not worry about all that, lets just target any link within the
pagination container. We can create a simple alert like this:

(function($){

$(document).on('click','.navlinksa',function(event){

event.preventDefault();

alert('ClickedLink');

})

})(jQuery);

simplealert.jshostedwith

byGitHub

viewraw

Note that everything is wrapped in an anonymous function. I recommend you do the


same. Take a look at this thread on why this is helpful. Ive created a click event,
prevented the default functionality from ring (i.e. loading the page) and Ive
alerted some text.

Creating an AJAX Call


Instead of working with client side data (alerting a preset text) we should grab some
dynamic data from the server side. Well need to do a tiny amount of prepwork.
Heres why: We need to give the AJAX call a URL to work with. Our Javascript le has
no knowledge of our environment, so we cant use something like
get_stylesheet_directory_uri()

in there. We can, however, use a localization technique to

pass variables to our JavaScript. Lets do that now in our functions le:

wp_localize_script('ajaxpagination','ajaxpagination',array(

https://premium.wpmudev.org/blog/loadpostsajax/

5/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

));

'ajaxurl'=>admin_url('adminajax.php')

localizescript.phphostedwith

byGitHub

By adding this code inside the


ajaxpagination

viewraw

my_enqueue_assets()

function we will have dened the

object (parameter 2). The object will receive its members according to

the array supplied as the third parameter in the

wp_localize_script()

words, once weve added this code we should be able to use


dene the URL to the

adminajax.php

function. In other

ajaxpagination.ajaxurl

to

which we use to handle AJAX calls.

The reason this works is that the localization function outputs the denition of this
object before our JavaScript is loaded. It looks something like this:

<scripttype='text/javascript'>

/*<![CDATA[*/

varajaxpagination={"ajaxurl":"http:\/\/wordpress.local\/wpadmin\/adminajax.php"};

/*]]>*/

</script>

localizescript.htmlhostedwith

byGitHub

viewraw

Getting back to our JavaScript le, we now have everything we need to build an AJAX
call. Heres how:

$(document).on('click','.navlinksa',function(event){

event.preventDefault();

$.ajax({

url:ajaxpagination.ajaxurl,

type:'post',

data:{

},

success:function(result){

10

11

12

})

13

})

ajaxcall.jshostedwith

action:'ajax_pagination'

alert(result);

byGitHub

https://premium.wpmudev.org/blog/loadpostsajax/

viewraw
6/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

As you can see the

function is what were using here. There are special

$.ajax()

functions for post and get methods but I prefer using this function because of its
exibility. You can read about all the parameters in the jQuery Documentation.
Using the

url

should be the

parameter we pass the URL of the script we want to send data to. This
adminajax.php

le which can be found in the

dened this above via the


The

type

is set to

post

directory. We

function.

wp_localize_script()

. We could also use

wpadmin

get

, our query is not too sensitive but I

prefer to post data unless the user needs access to the parameters.
The

data

parameter is an object which contains the data you want to pass. In our

case I will be able to access a


ajax_pagination

Finally, the

$_POST['action']

variable, the value of which would be

. You can pass as many as your application requires of course.

success

parameter is

a function which alerts the


result of our AJAX call. Well
make this a bit fancier below,
for now this is sucient for

0 is returned if no server-side code is written.

testing. If you try clicking on a


link now it actually works but
wont be very useful since we havent dened the server side code. In fact, what you
should see alerted is

0.

So why does this happen? When I said we havent dened server side code, I
wasnt entirely truthful. We havent, but WordPress has. There is some content in
the

adminajax.php

le we are using. If you take a look at the source code of that le

you should see that the script uses

https://premium.wpmudev.org/blog/loadpostsajax/

die('0')

in a couple of cases.

7/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

1.6 million WordPress Superheroes read and trust our blog. Join them and get daily posts
delivered to your inbox - free!
Email address

SUBSCRIBE

If we dont supply an action the

adminajax.php

script dies and returns 0. If we do

supply an action but we dont hook into the required WordPress hooks nothing
happens and at the very end of the le we die again, returning 0. In conclusion we
are already communicating with the server.

Communicating With WordPress


To get a meaningful answer from WordPress we need to dene some WordPress
actions. This is done using a set pattern. Lets dive in by continuing our example in
the functions le of our theme:

add_action('wp_ajax_nopriv_ajax_pagination','my_ajax_pagination');

add_action('wp_ajax_ajax_pagination','my_ajax_pagination');

functionmy_ajax_pagination(){

echoget_bloginfo('title');

die();

ajaxaction.phphostedwith

byGitHub

Ive hooked a function to two hooks. Hooks that take on the

viewraw

wp_ajax_[action_name]

format are only executed for logged in users. Hooks that take on the
wp_ajax_norpiv_[action_name]

format are only executed for non-logged in users. The great

https://premium.wpmudev.org/blog/loadpostsajax/

8/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

benet of this is that you can very easily separate functionality.


The action names I mentioned above refer to the action dened in our AJAX call in
Javascript (

action:'ajax_pagination'

anything you like, I used

) they must match. The function name can be

my_ajax_pagination

for clarity.

The function itself can contain anything youd like. You can log out users, grab their
data, publish a post and so on. Whatever you want to return to Javascript you must
echo. In the example above Ive echoed the title of the blog, pulled in dynamically
via the

get_bloginfo()

function.

The nal step is to use


adminajax.php

die()

. If we dont dene this, the die function dened in

at the very end of the le will kick in and you will end up echoing

in

addition to whatever else you are echoing. If you try out the code above you should
now see the title of your website returned.

Overview
That concludes our basic example! Before we move on to pulling in posts via AJAX,
lets quickly recap the steps necessary to perform an AJAX action:
Enqueue a Javascript le if you dont already have one
Use

wp_localize_script()

to pass the URL of your

adminajax.php

le

Create the AJAX call in Javascript


Hook a function using the appropriate hook name
Code the function which may return data back to Javascript

Loading Posts With AJAX


Now for the juicy stu! I started this project by writing the JavaScript code for it.
Without further ado, here is the basic version. Well expand on it with some tweaked
https://premium.wpmudev.org/blog/loadpostsajax/

9/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

user experience soon.

(function($){

functionfind_page_number(element){

element.find('span').remove();

returnparseInt(element.html());

$(document).on('click','.navlinksa',function(event){

event.preventDefault();

10

11

page=find_page_number($(this).clone());

12

13

$.ajax({

14

url:ajaxpagination.ajaxurl,

15

type:'post',

16

data:{

17

action:'ajax_pagination',

18

query_vars:ajaxpagination.query_vars,

19

page:page

20

},

21

success:function(html){

22

$('#main').find('article').remove();

23

$('#mainnav').remove();

24

$('#main').append(html);

25

26

})

27

})

28

})(jQuery);

ajaxpagination.jshostedwith

byGitHub

viewraw

This is much the same as our basic example. The rst thing youll notice is that Ive
added a way to detect which page the user wants to request. Each link has a

span

element in it which is hidden (it is there for screen readers). I make a clone of the
element to make sure I dont modify the original, remove the span and parse the
remainder as an integer. This gives us the page number we need.
I will also need to know the query parameters used. On the main page this is pretty
simple, its just the

paged

parameter since were working with the default query. If

we start o on an archive page (like a category archive) well need to know the
https://premium.wpmudev.org/blog/loadpostsajax/

10/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

category name as well.


Well pass the query variables using the localization method we learned earlier. For
now well use

ajaxpagination.query_vars

success we remove all

article

even though this is not yet dened. Finally, on

elements from the main container, we remove the

pagination element and append the return value of our AJAX call to the main
container.
This return value will contain the posts and the new navigation element. Note that
Ive changed the name of the parameter from

response

to

html

because it makes a bit

more sense. To nish up we use the localization array to pass the original query
parameters.
The following function should be placed in our

my_enqueue_assets()

function replacing

the localization we had earlier:

global$wp_query;

wp_localize_script('ajaxpagination','ajaxpagination',array(

'ajaxurl'=>admin_url('adminajax.php'),

'query_vars'=>json_encode($wp_query>query)

));

finallocalization.phphostedwith

byGitHub

All we need to do now is esh out the

viewraw

my_ajax_pagination()

function. Whatever this

function echoes will replace the content on our page. Heres the nal code with an
explanation below:

add_action('wp_ajax_nopriv_ajax_pagination','my_ajax_pagination');

add_action('wp_ajax_ajax_pagination','my_ajax_pagination');

functionmy_ajax_pagination(){

$query_vars=json_decode(stripslashes($_POST['query_vars']),true);

$query_vars['paged']=$_POST['page'];

https://premium.wpmudev.org/blog/loadpostsajax/

11/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

10

$posts=newWP_Query($query_vars);

11

$GLOBALS['wp_query']=$posts;

12

13

add_filter('editor_max_image_size','my_image_size_override');

14

15

if(!$posts>have_posts()){

16

get_template_part('content','none');

17

18

else{

19

while($posts>have_posts()){

20

$posts>the_post();

21

get_template_part('content',get_post_format());

22

23

24

remove_filter('editor_max_image_size','my_image_size_override');

25

26

the_posts_pagination(array(

27

'prev_text'=>__('Previouspage','twentyfifteen'),

28

'next_text'=>__('Nextpage','twentyfifteen'),

29

'before_page_number'=>'<spanclass="metanavscreenreadertext">'.__('Page','twentyfifteen')

30

));

31

32

die();

33

34

35

functionmy_image_size_override(){

36

returnarray(825,510);

37

my_ajax_pagination.phphostedwith

byGitHub

viewraw

Using our passed parameters we build a custom query. This involves basically taking
the query variables we passed and making sure that the page number we passed
overwrites the

paged

parameter. We then use our nal

$query_vars

array to create a

new query.
We need to make the

$GLOBALS['wp_query']

reason we need to do this is that the

variable equal to our new posts object. The


the_posts_pagination()

function uses this global

variable.
Next, notice that Ive added a function to the
https://premium.wpmudev.org/blog/loadpostsajax/

editor_max_image_size

lter and a few rows


12/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

down I remove it. This was something unexpected that came up. I actually created a
WordPress Trac Ticket. We may see some progress on it! Heres the issue:
When images are loaded in the post they all look just ne. However, if you complete
this tutorial without these lters your images will be narrower, only 660px wide
instead of the necessary 825px. The reason for this is that the function that loads the
images eventually calls a function named

image_constrain_size_for_editor()

. This function

makes sure that images in the post editor arent too wide. To determine weather this
size reduction should take place it uses the
through

adminajax.php

is_admin()

function. Since our code runs

which technically is in the admin, WordPress scales our images

down, mistakenly thinking we are using them in the editor.


Luckily we can use the

editor_max_image_size

lter to determine the maximum size for

the editor. Since we want to leave everything as is, except for during our AJAX call
we add the lter using our custom values (

array(825,510)

) and then immediately

remove it just to make sure it doesnt cause trouble anywhere else.


The next step is to use our query to list our posts. I copied a lot from the

index.php

le

in the parent theme. if there are no posts we use the template which is meant to
handle that, otherwise we loop through the posts and use the post display template.
Finally we use the same pagination format we see in the index le.

A Note About AJAX Calls


Its important to remember that AJAX calls are always considered to originate from
the admin. What this means is that draft, scheduled and private posts may be
returned with this call. If you dont want this to happen, youll need to control the
behaviour with appropriate parameters such as

post_status

Better User Experience


WithAJAX solutions like this, it is extremely important to focus on user experience.
Im working in a local environment so everything loads really quickly, but on a
https://premium.wpmudev.org/blog/loadpostsajax/

13/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

production server images and other assets may takemoretime to load.


Due to this you should at least add a loader or loading text and disable further clicks
on the navigation elements. We will take care of these by making the posts and the
navigation disappear right after the user clicks and displaying the text loading new
posts. When the success event res we remove the loading text and display the
posts. Heres our updated AJAX call:

$.ajax({

url:ajaxpagination.ajaxurl,

type:'post',

data:{

action:'ajax_pagination',

query_vars:ajaxpagination.query_vars,

page:page

},

beforeSend:function(){

10

$('#main').find('article').remove();

11

$('#mainnav').remove();

12

$(document).scrollTop();

13

$('#main').append('<divclass="pagecontent"id="loader">LoadingNewPosts...</div>

14

},

15

success:function(html){

16

$('#main#loader').remove();

17

$('#main').append(html);

18

19

})

ux.jshostedwith

byGitHub

We now have a separate

viewraw

beforeSend

and

success

function. The former is performed as

soon as you click the link, before the AJAX call is sent to the server. The later is
performed once we receive data back from the server.
Before the call is sent we remove the articles and the navigation. This makes sure
users cant keep clicking on navigation links while theyre waiting for things to load.
Next we scroll to the top of the document. Then, we append a loading notication to
make it clear to users whats going on. Ive used the same markup as Twenty Fifteen
https://premium.wpmudev.org/blog/loadpostsajax/

14/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

uses on post-not-found pages. In the success function we remove the loader and
load our content, all done!

AJAX Pitfalls
AJAX is extremely powerful; apart from loading posts you can perform all sorts of
actions via AJAX calls. There are quite a number of dangers and things to look out for
while using it, here are a few:
Safety can be a major concern. If you want to delete a post via AJAX you need to
make sure the user has the intent and the permission (using nonces), for example.
When using regular methods WordPress has built-in protections in some cases but
with AJAX you usually have to think of this on your own.
Graceful degradation is another facet of AJAX, although something that is becoming
less important. Basically: no JavaScript, no AJAX. If you rely on AJAX heavily, users
who have it disabled will not be able to use our application. Javascript has become so
ubiquitous that this is almost irrelevant, but may come up in some situations. In this
case you need to make sure that clicking on the actual link will work as well.
User experience is very frequently overlooked. AJAX functionality is indeed cool, but
a reliably working website is cooler. Users are used to pages loading when they click
links. You need to make everything very transparent, users should know what is
going on and why. You should use AJAX to enhance your work, not to bring as much
bling as you can to the table.

Overview
As you can see, implementing AJAX requires a bit of preparation and practice but
once its second nature youll nd that it comes easily. It probably took you a while
to read through this and it will take even more time to do it for the rst time, but I
coded the whole example in about 15 minutes.
https://premium.wpmudev.org/blog/loadpostsajax/

15/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

AJAX is one of those techniques which can be dicult because it encompasses


almost all programming languages used in a framework like WordPress. Things are
spiced up further by having to adhere to conventions like hooks and localization.
Practice makes perfect. I guarantee youll fall in love AJAX if you start to use it.
Have you implemented AJAX on your site? What other uses are there for AJAX in
WordPress? Let us know what you think in the comment below.

Share this post!

SHARE ON FACEBOOK

SHARE ON TWITTER

SHARE ON GOOGLE+

Fancy some more reading?

HOW TO USE AJAX IN WORDPRESS TO

YOUR TOTALLY COMPLETE GUIDE TO

LOAD SEARCH RESULTS

CUSTOMIZING THE WORDPRESS POST


EDITOR

https://premium.wpmudev.org/blog/loadpostsajax/

16/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

Or how about trying out our plugins and themes for


free?
Test out your WordPress Superpowers and give your site a boost with all our plugins, themes,
services and our full support, free for 14 days - no catch!

HUMMINGBIRD

DEFENDER

Everything you need to get


your site running super fast.

SNAPSHOT PRO

Regular security scans,


vulnerability reports, safety
recommendations

WP SMUSH PRO

A WordPress Time Machine


to backup and restore your
entire site.

Incredibly efcient image


optimization for blazing fast
load times.

Interested?

Try out 100+ Premium Plugins, Upfront Themes, WP Defender,


Hummingbird Performance, 24/7 Expert WP Support, Snapshot
https://premium.wpmudev.org/blog/loadpostsajax/

17/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

Backups & more - FREE for 14 Days


START FREE TRIAL

LEARN MORE

32 Responses
mark_szymanski

3 pts

0 pts

Regular Joe
LEVEL 0

Awesome post! Im just starting to incorporate AJAX into some of my themes, this article
is super thorough.
Any difference between:
$(document).on( click, .nav-links a, function( event ) {
and
$(.nav-links a).on( click, function( event ) {
Thanks!

https://premium.wpmudev.org/blog/loadpostsajax/

18/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

January 22, 2015, 11:43 am

Daniel Pataki
29 pts

49 pts

Author

LEVEL 2

Hi Mark,
Thank you :) yes there is indeed. The rst one is favoured because the second one
will not be bound to links loaded via ajax.
For example: You could load comments via ajax on archive pages. If you also have
AJAX pagination loading comments will fail for articles loaded via AJAX because at

the time the document loaded the .nav-links a for the new articles did not exist.
Hope that makes sense! Take a look at the documentation of the on function. Im not
extremely well versed in Javascript so my explanations are not that good :)
http://api.jquery.com/on/
Daniel

January 22, 2015, 11:49 am

mark_szymanski

3 pts

0 pts

Regular Joe
LEVEL 0

Ahhh, that makes sense. Cheers

January 22, 2015, 2:24 pm

pingram3541

6 pts

0 pts

Regular Joe
LEVEL 0

https://premium.wpmudev.org/blog/loadpostsajax/

19/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

Thanks for the write up.


How could this impact SEO?
Is it assumed or known that when crawled, the original links will be followed and still load
as if the ajax was not even built or have the search engines evolved to the point that they
now follow the course of the manipulated DOM and js events?
Clicking the nav links doesnt change the url so we should also consider how this might
also affect things like clicking a share this link that may now not have the correct url to
get to that specic page level, right?

January 23, 2015, 1:35 pm

Daniel Pataki

29 pts

49 pts

Author

LEVEL 2

Hi There :)
Let me address the share this link issue. Generally there is no share this link for
paginated archives since the articles on any given page change all the time. The
articles themselves do have share this links but these are loaded with the articles so
they should point to the correct place.
In general, AJAX can impact SEO negatively. However, there are ways to circumvent
this, take a look here for example:
http://moz.com/blog/create-crawlable-link-friendly-ajax-websites-using-pushstate
Also, I would argue that SEO is less important in many cases (not all) than user
experience. Im sure many people would argue against me so this is just my view. If
Im looking to buy headphones I really dont care about who comes up rst on
Google. I will buy from the company who has a website that allows me to browse
through headphones nicely.
Daniel

January 23, 2015, 2:34 pm


https://premium.wpmudev.org/blog/loadpostsajax/

20/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

pingram3541

6 pts

0 pts

Regular Joe

LEVEL 0

Youre absolutely right about the share link not typically being used in this type of
view and I should have claried I was only using that as an example as
something that may reference the current document url which in this example
doesnt change with the content.
I agree with you regarding user experience being top dog but that will never
come into play if the trafc never follows =)
Based on my initial inquiry and reading the article you referenced, should I be ok

seo-wise provided all ajax-ied links can be followed and indexed normally, such
as real paths that present the same content as the ajax counter-part that
prevents the default event normally?

January 23, 2015, 5:45 pm

Daniel Pataki

29 pts

49 pts

Author

LEVEL 2

Hello again :)
Quick warning: do take everything I say about SEO with a pinch of salt, i am
nowhere near an expert on it. In addition I have a built in aversion to it because I
feel that too many people focus too much on SEO instead of providing quality
content. I have no issues with folks writing great content going for SEO but it
should be content rst, SEO second, not the other way around :)
I have the feeling were on one page about this so enough said :)
I believe that yes, you should be ok seo-wise if you make sure everything works
based on the article. In addition, you may not need to do anything in some cases.
With pagination the link actually exists anyway so Google CAN parse all the
https://premium.wpmudev.org/blog/loadpostsajax/

21/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

pages, even if the user sees them loading with AJAX.


I usually follow this tactic: If you switch of javascript can you navigate to the
page? If so, I dont worry about SEO losses because of AJAX too much.

January 23, 2015, 5:54 pm

pingram3541

6 pts

0 pts

Regular Joe
LEVEL 0

Perfect, you see what we just did there? We keyword laced your article comments for

better SEO =)

January 23, 2015, 7:07 pm

Daniel Pataki
29 pts

49 pts

Author

LEVEL 2

Hah yes! SEO comments, theres a new one :D

January 24, 2015, 2:06 am

Andy

0 pts

Regular Joe
0 pts

LEVEL 0

Hi,
Nice tutorial, I used some parts of it on my new website!
Only one problem with this: If you schedule posts, it will cause duplicate posts with a
custom theme (didnt test it with the default themes). This is because the post status is
https://premium.wpmudev.org/blog/loadpostsajax/

22/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

not dened in the AJAX function.


A solution for this is to add this $query_vars[post_status] = publish; after
$query_vars[paged] = $_POST[page];

February 17, 2015, 9:28 am

Eric

6 pts

Regular Joe
0 pts

LEVEL 0

Many thanks for this article. Im in the process of redesigning my photoblog

(http://www.pixelfan.be/) and was looking for a comprehensive tutorial about ajax. Some
of my archive pages with pictures take much too long to load and I didnt know how to
implement ajax and pagination now I know thanks to your article. Its clear, not too long
or technical and even an amateur like me was able to understand it :-)
Thanks for this !

March 16, 2015, 6:29 am

Daniel Pataki

29 pts

49 pts

Author

LEVEL 2

Hi Eric, thanks so much for the kind words, Im glad it was of use to you :)

March 16, 2015, 6:31 am

Eric

6 pts

Regular Joe
0 pts

LEVEL 0

Youre welcome :-)


When youre not a professional webdesigner and depend on what you nd on the
https://premium.wpmudev.org/blog/loadpostsajax/

23/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

internet to solve your questions/problems youre often dissapointed by the info


you nd.
So its always great to nd wellwritten articles like yours. Keep up the good work !

March 16, 2015, 10:53 am

Nick Bullets

0 pts

0 pts

Regular Joe

LEVEL 0

Hi Daniel,
s
Thank you so much for publishing this article! We ALL appreciate it.
The Better UX section is great and with a Font Awesome spinner icon, its even funner.
The only Im having is, the initial AJAX call is so short that the Loading New Posts is
only visible for a moment and then proceeds to loading large images slowly.
Is there a better way to handle the individual content thats loaded (e.g. large images)
AFTER the success function in the AJAX call?
Thanks again,
Nik

March 20, 2015, 2:03 am

Daniel Pataki

29 pts

49 pts

Author

LEVEL 2

Thanks Nik, Im glad you like it :)


You need to lazy load your images, take a look at something like this:
http://www.appelsiini.net/projects/lazyload/enabled_ajax.html
Daniel
https://premium.wpmudev.org/blog/loadpostsajax/

24/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

March 20, 2015, 2:14 am

Nick Bullets

0 pts

0 pts

Regular Joe

LEVEL 0

Thanks for the tip! It was helpful.


In circumstances where you arent targeting a given pagination id number (like in
this case) and youve reached the max related posts from the query, is there a
method for knowing when youve reached the end using query_vars?
s

Thank you,
Nik

March 21, 2015, 3:42 am

Daniel Pataki

29 pts

49 pts

Author

LEVEL 2

Hi Nik,
Yep, there is! I recommend always printing things out when in doubt to see
what info you have. Just print the value of $wp_query, I like to use this
format:
You can also take a look at the docs:
https://codex.wordpress.org/Class_Reference/WP_Query
There are two properties youll need: post_count and found_posts.
$found_posts contains the number of posts that are found in the database
in total, the $post_count property shows the number on the current page.
So if you have 18 posts in category A and you query for them, on page two
found_posts will be 18 and post_count will be 8.
https://premium.wpmudev.org/blog/loadpostsajax/

25/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

You can also look at the $max_num_pages which is probably better in your
case, this shows the total amount of pages you need to display the results.
Hope this helps,
Daniel

March 21, 2015, 8:02 am

Nick Bullets

0 pts

0 pts

Regular Joe

LEVEL 0

s
Hey Daniel,
I really appreciate you taking the time to respond. Its a rarity these days.
I guess the only issue is passing the $found_posts back to the JS if my
function to query the posts is outside the function to enqueue my
assets (wp_localize_script). If there was a way to pass $found_posts to
wp_localize_script much like ajaxurl is passed to JS, then that would
solve everything.
Its interesting because the topic of this blog post is a fairly common
use case and yet, there are very few articles on the subject, and even
less so with the quality of your article.
Thank you again.

March 21, 2015, 2:22 pm

Daniel Pataki

29 pts

49 pts

Author

LEVEL 2

Hi Nik,

https://premium.wpmudev.org/blog/loadpostsajax/

26/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

Thanks for the kind words :) Ah, I see. There are a few ways around this.
If pagination is the only lter you have then you could output the
pagination itself via jQuery as well.
Instead of just loading the posts you put the pagination functionality in
there are well. That way the correct structure is returned back and you
dont need to worry about it.
In general, there are two ways you can solve this. One is to just return all
the UI components. This is a bit wasteful but isnt THAT bad.
The other way is to store the current query variables somewhere in the
DOM. Instead of returning HTML with your jQuery you could return an
array. The rst member would return the HTML, the second a json
encoded string of the query variables. You could stash this in a hidden

div and pass it to the AJAX call each time.


There are some more elegant ways of handling this by adding the
variables as data parameters to a parent element perhaps.
Hope this helps!
Daniel

March 21, 2015, 4:05 pm

Dion

0 pts

Regular Joe
0 pts

LEVEL 0

Hi,
When I created the child theme, I noticed that even though the style.css le had no entries
other than the comments, the site looked no different. My conclusion is that the child css
le is loaded after the parent one, thus overwriting any parent settings you set in the child
css?

April 3, 2015, 6:35 am

https://premium.wpmudev.org/blog/loadpostsajax/

27/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

Daniel Pataki

29 pts

49 pts

Author

LEVEL 2

Thats correct Dion :)

April 3, 2015, 8:15 am

Dion

0 pts

Regular Joe
0 pts

LEVEL 0

Codex seems to say that the parent css needs to be queue as well:add_action( wp_enqueue_scripts, theme_enqueue_styles );
function theme_enqueue_styles() {
wp_enqueue_style( parent-style, get_template_directory_uri() . /style.css );
wp_enqueue_style( child-style,
get_stylesheet_directory_uri() . /style.css,
array(parent-style)
);
}

April 3, 2015, 8:58 am

Mathias

0 pts

0 pts

Regular Joe

LEVEL 0

Thanks for this great tutorial!


I am having difculties getting the previous posts and next posts link to work. If i click
on Page 1 or Page 2 everything works as intended, but if i click on next posts or
previous posts nothing happens. I am pretty knew to ajax and cant gure how to x this
problem. Any help is greatly appreciated.
https://premium.wpmudev.org/blog/loadpostsajax/

28/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

April 15, 2015, 10:53 am

Dean

0 pts

Regular Joe
0 pts

LEVEL 0

Im trying to do something similar, I have removed the post content on comment pages
that exceed comment page # 1 by adding the following php statement.
global $cpage; if( $cpage <= 1 ) get_template_part( 'content', get_post_format() );
Actually I just added " global $cpage; if( $cpage <= 1 )" to the default statement and it

works like a charm, gure removing the post content is a good way to avoid duplicate
content and most forums are laid out like that anyway. Now If deemed necessary I would
like to load the post content back into the page by adding a link that says "load original
post".
Strangely enough, I found a function in the function.php that is name ajax_show_post and
when I call it, it loads the post content, but not-in-the-page.
I know you probably already have in your tutorial above, but I'm having trouble converting
it for my needs. If you can give a brief summary of what I need to do to get it to work for
my situation, I'll see if I can sort it out.
In the mean time I'm going to go through your tutorial again and again. thxs

May 4, 2015, 7:21 pm

Kevin Zerbo

0 pts

0 pts

Regular Joe

LEVEL 0

Uhwheres the code?

May 6, 2015, 5:50 pm


https://premium.wpmudev.org/blog/loadpostsajax/

29/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

Kevin Zerbo

0 pts

0 pts

Regular Joe

LEVEL 0

Uhwheres the code??

May 6, 2015, 5:50 pm

Dean

0 pts

Regular Joe
0 pts

LEVEL 0

Uhwheres the code???


OK you got it and since this post might get a bit lengthy, let me make it more so, by resummarizing what Im trying to accomplish.
When viewing single posts I removed the post content to display just the remaining
comments, if, comments are paged and the comment page is greater than (1).
Reasoning: cuts down on redundancy, speeds page load, avoids duplicate content, etc..
That was the simple part, now Id like to provide a link to load the missing content back
into the page. My reasoning there is, maybe youre twenty pages into the comments and
need to double check some minutia that was implied in the original post to base your
response on. In my case since Im only displaying the comment form on the page that the
last comment resides, loading the post content in-line can save a lot needless navigation.
Etcetera wise, therere to many to list, so lets just take the main one, I WANT THIS
FUNCTIONALITY.
I cant believe that upon the millions upon millions of WordPress installs out there Im
the only one trying to implement this feature, but that seems to be the case?
Anyways, a few days ago when I made my rst comment here, I thought I was 60% of the
way towards having a working solution, now due to some inexplicable bug I hadnt noticed
with the preexisting function I confessed to having,,, I might have to revise the 60%
downward signicantly. Maybe not though, maybe the problem is something simple that
https://premium.wpmudev.org/blog/loadpostsajax/

30/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

Im over looking, more on the problem when I get that far. Now to borrow a phrase that
Daniel used in his tutorial above
Without any further ado heres what I do have so far.
I have created and placed in my themes js folder a java-script le aptly named
show_post.js. I havent really started on it yet and what I do have may look something
like this
************************************
if (code == poetry) Dean < Poetic;
echo " A script of a thousand characters begins with a single keystroke;
// eof
************************************

Next, pretending the java script is in working order and if Ive read the tutorial right, we
need to add a snippet to functions.php to enqueue and localize the script. Realistically
most posts are not going to garner enough comments to ever generate additional
comment pages, so a conditional statement might be prudent to prevent unnecessary
loading of the script.
************************************
global $cpage;
if ( is_singular() && $cpage > 1 ) {
wp_enqueue_script( show_post, get_stylesheet_directory_uri() . /js/show_post.js, array(
jquery ), 1.0, true );
wp_localize_script( show_post, showpost, array(ajaxurl => admin_url( admin-ajax.php
)));
}
************************************
Here is the problematic function that echos the post content.
/***********************************
* Show a single post via admin-ajax.php
*
* Use a url like this to call this function:
* /wp-admin/admin-ajax.php?action=show_post&p=514
*
https://premium.wpmudev.org/blog/loadpostsajax/

31/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

*/
function show_post() {
$id = ( isset( $_GET[p] ) ) ? (int) $_GET[p] : false;
query_posts( array( p => $id ) );
if ( have_posts() ) :
// Start the Loop.
while ( have_posts() ) : the_post();
get_template_part( content, get_post_format() );
endwhile;
else :
// If no content, include the No posts found template.
get_template_part( content, none );
endif;

die();
}
add_action( wp_ajax_show_post, show_post );
add_action( wp_ajax_nopriv_show_post, show_post );
Can someone tell me what the H-E-(TOOTHPICK X 2) is wrong with that? What Im
experiencing is when the function is called as prescribed, it only works correctly if the
user is logged in as admin. All other users end up with the
else : get_template_part( content, none ); // makes no sense.
************************************
LASTLY: Remove the post content where appropriate and provide a link to trigger the
javascript. Cant say Ive got that completely done either, whats left is not an issue. For
testing purposes what I do have calls the function directly. The code below replaces the
get_template_part( content, get_post_format() ); in the single.php.
************************************
<?php
global $cpage;
if( $cpage <= 1 ) get_template_part( 'content', get_post_format() );
elseif( $cpage > 1)
echo '<a ID="',$post->ID,'" class="show-post" rel="nofollow" href="',get_site_url(),'/wpadmin/admin-ajax.php?action=show_post&p=',$post->ID,'">Load Original Post</a>';
https://premium.wpmudev.org/blog/loadpostsajax/

32/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

?>
************************************
Getting my head wrapped around what I need to do to make any headway on this project
has now annoyed me to the point where its no longer about enhancing the users
experience, getting it to work has become a matter of principle. And with that haughty
declaration Id also like to humbly add, Im not adverse to cheating, any help anyone can
provide will be greatly appreciated!

May 9, 2015, 2:25 pm

Michel

0 pts

Regular Joe
0 pts

LEVEL 0

Hi Daniel and thank you for your post. Would their be a way to adapt your solution to open
post through AJAX from a list of post ? instead of using the script just to load new pages.
I am trying to adapt your code and for instance:
When a post link is clicked:
$(document).on( click, .project-link, function( event ) {
do_ajax_request(this,event,$);
});
function do_ajax_request(element,event,$) {
event.preventDefault();
var url = $(element).attr( href );
history.pushState(null, null, url);
perform_ajax_request(url,$);
}
So you can see that Im trying to get the page URL and to pass this in the ajax request
instead of a page number.. Unfortunately im not sure how to adapt the action sent in the
ajax since the one you are saying to do seems to be working only for pages number
How could it work for post slugs instead ?
With something like that (not sure if it does work yet ) we could retrieve the slug:
return String(project_slug.substr(project_slug.lastIndexOf(/) + 1));
https://premium.wpmudev.org/blog/loadpostsajax/

33/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

and use that slug to pass to the PHP side, instead of a page number But Im stuck at
that point.. !
Thank you for your time,
Hope you can help!

May 28, 2015, 10:22 am

Daniel Pataki

29 pts

49 pts

Author

LEVEL 2

Hi Michael,

Do I understand correctly that you essentially want to load a whole URL via AJAX? If
this is the case, there is no real benet to using AJAX, since the while page needs to
be loaded. The other solution a bit too complex for a comment here is to just
load the content of the post.
I suggest using templates to display all your posts. So essentially this is how your
posts are loaded via PHP regularly:
<?php while( have_posts() ) : the_post() ?>
<div id=post-container>
<?php get_template_part( single, $post->post_type ) ?>
</div>
<?php endwhile() ?>
Now, whenever you click on a link, pass the ID via AJAX, just like I did. Instead of
showing a list of posts, just load a single one on the AJAX side and pass the content
to Javascript, then display it within the #post-container div. Something like this:
function my_post_loader() {
$post_id = $_POST[post_id]; // this was passed via AJAX
$args = array(
include => array( $post_id ),
post_type => any
);
https://premium.wpmudev.org/blog/loadpostsajax/

34/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

$posts = new WP_Query( $args );


while( $posts->have_posts() ) {
the_post();
ob_start();
get_template_part( single, $post->post_type )
$content = ob_get_clean();
}
echo $content;
die();
}
s

Hope this helps!


Daniel

May 28, 2015, 11:55 am

Michel

0 pts

Regular Joe
0 pts

LEVEL 0

Yes Daniel. I might have not been clear (english is not my native language eheh).
But I found the answer to my problem somewhere else. (in french sorry, but great
article if ever wanting to adapt in english: http://www.seomix.fr/ajax-wordpress/)
It is basically doing the same idea that you answered in your comment. Using
main template, then ajax-templates that are shrinked in content. It is also giving
a solution to make all of that seo friendly (with push state / pop state as
described in one of your comment above) and making the navigation full ajax
(what I was looking for). There is also a solution in case someone doesnt have
javascript activated, which is great!
thank you for your time and your comment :)

May 28, 2015, 5:08 pm


https://premium.wpmudev.org/blog/loadpostsajax/

35/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

Mansukh

0 pts

0 pts

Regular Joe

LEVEL 0

Thank you for post awesome article. I need in WP USER Pagination using
WP_user_Query how can i set pagination on user table.
I think need to change the_posts_pagination() to any other but i have no any idea how
can i set..
thanks so much in advance.
s
August 4, 2015, 2:53 am

Stephen

1 pts

1 pts

Regular Joe

LEVEL 0

Thanks for the excellent post. This covers the main thing that many other tutorials dont
how to make the pagination apply to all of your archives (dynamically populating the
query vars), rather than, just say, the homepage, where you can hard code the query.
However, I have one question is this actually safe? If you use the code youve shown, I
can pass my own custom query parameters, thus getting the results of any call to
query_posts that I like. For example, I could request draft posts, or private posts, or media
items, or anything at all that I probably shouldnt have access to.
I guess the handling code could override some variables such as always setting
post_status to publish but its hard to know what should be allowed and what shouldnt
when youre wanting pagination throughout your whole blog, categories, tags, custom
post types, etc.
What do you recommend to avoid this?

January 19, 2016, 5:45 pm


https://premium.wpmudev.org/blog/loadpostsajax/

36/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

Comments are closed.

1.6 million WordPress Superheroes read and trust our blog. Join them and get daily posts
delivered to your inbox - free!
Email address

SUBSCRIBE

JOIN
1 2 3 , 4 5 6

HAPPY MEMBERS
We pride ourselves on our level of customer support and responsiveness
to member requests. Your WordPress experience will never be the same

https://premium.wpmudev.org/blog/loadpostsajax/

37/38

16/6/2016

LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV

100+ Premium Plugins - The Upfront Theme - Unlimited Superhero Support

START 14 DAY FREE TRIAL

Terms of Service Privacy Policy Contact


2004-2016 WPMU DEV - Project by Incsub

https://premium.wpmudev.org/blog/loadpostsajax/

38/38

You might also like