Professional Documents
Culture Documents
LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV
#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
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.
2/38
16/6/2016
LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV
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.
js
folder and a
ajaxpagination.js
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()
ajaxpagination.js
alert('ScriptIsEnqueued')
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
next
pagenumbers
nav
. 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
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
viewraw
my_enqueue_assets()
object (parameter 2). The object will receive its members according to
wp_localize_script()
adminajax.php
function. In other
ajaxpagination.ajaxurl
to
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
$.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
type
is set to
post
directory. We
function.
wp_localize_script()
wpadmin
get
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
Finally, the
$_POST['action']
success
parameter 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
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
adminajax.php
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.
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
viewraw
wp_ajax_[action_name]
format are only executed for logged in users. Hooks that take on the
wp_ajax_norpiv_[action_name]
https://premium.wpmudev.org/blog/loadpostsajax/
8/38
16/6/2016
LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV
action:'ajax_pagination'
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.
die()
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()
adminajax.php
le
9/38
16/6/2016
LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV
(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
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
ajaxpagination.query_vars
article
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
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
global$wp_query;
wp_localize_script('ajaxpagination','ajaxpagination',array(
'ajaxurl'=>admin_url('adminajax.php'),
'query_vars'=>json_encode($wp_query>query)
));
finallocalization.phphostedwith
byGitHub
viewraw
my_ajax_pagination()
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
$query_vars
array to create a
new query.
We need to make the
$GLOBALS['wp_query']
variable.
Next, notice that Ive added a function to the
https://premium.wpmudev.org/blog/loadpostsajax/
editor_max_image_size
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()
editor_max_image_size
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)
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.
post_status
13/38
16/6/2016
LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV
$.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
viewraw
beforeSend
and
success
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
SHARE ON FACEBOOK
SHARE ON TWITTER
SHARE ON GOOGLE+
https://premium.wpmudev.org/blog/loadpostsajax/
16/38
16/6/2016
LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV
HUMMINGBIRD
DEFENDER
SNAPSHOT PRO
WP SMUSH PRO
Interested?
17/38
16/6/2016
LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV
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
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
mark_szymanski
3 pts
0 pts
Regular Joe
LEVEL 0
pingram3541
6 pts
0 pts
Regular Joe
LEVEL 0
https://premium.wpmudev.org/blog/loadpostsajax/
19/38
16/6/2016
LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV
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
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?
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
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 =)
Daniel Pataki
29 pts
49 pts
Author
LEVEL 2
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
Eric
6 pts
Regular Joe
0 pts
LEVEL 0
(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 !
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 :)
Eric
6 pts
Regular Joe
0 pts
LEVEL 0
23/38
16/6/2016
LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV
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
Daniel Pataki
29 pts
49 pts
Author
LEVEL 2
24/38
16/6/2016
LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV
Nick Bullets
0 pts
0 pts
Regular Joe
LEVEL 0
Thank you,
Nik
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
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.
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
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?
https://premium.wpmudev.org/blog/loadpostsajax/
27/38
16/6/2016
LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV
Daniel Pataki
29 pts
49 pts
Author
LEVEL 2
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)
);
}
Mathias
0 pts
0 pts
Regular Joe
LEVEL 0
28/38
16/6/2016
LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV
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
Kevin Zerbo
0 pts
0 pts
Regular Joe
LEVEL 0
29/38
16/6/2016
LoadingWordPressPostsDynamicallyWithAJAXWPMUDEV
Kevin Zerbo
0 pts
0 pts
Regular Joe
LEVEL 0
Dean
0 pts
Regular Joe
0 pts
LEVEL 0
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!
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!
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
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 :)
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?
36/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
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
https://premium.wpmudev.org/blog/loadpostsajax/
38/38