Build 10 games and learn game development along the way in this fast paced game development course

Get the source code of 12 commercial games, loaded 50+ million times, and learn the secrets of game design

Learn how to make a successful Flash game from a real world example. Fully commented source code

Create realistic Flash physics games from scratch with advanced features, from Angry Birds to Crush the Castle

Loading WordPress posts with Ajax and jQuery

After seeing how to include jQuery Ajax calls in your WordPress blog, it’s time to load posts on the fly, without reloading the page.

As for the previous example I am using the standard Kubrick theme… without any plugin installed.

Look how I load the posts under the header by clicking on their titles… even the ones with “more” tag appear complete without reloading the page:

Let’s start with header.php modifications

This is the script I added under

That is the JQuery part

I already explained the first 4 lines in the previous tutorial.

Line 5: Waiting for the user to click on an hypertext over an h2 heading. I am doing it because in Kubrick post titles are rendered this way:

This should change from theme to theme, but this works on Kubrick

Line 6: Retrieving the rel attribute of the link and saving it in a variable called post_id. You’ll see later in this tutorial how this attribute will contain the unique ID of the post we want to show.

Line 7: In an element with your_post_here id I am writing “loading…” because I’m starting to load the post. You’ll see later in this tutorial where to place the element

Line 8: Now thw ajax magic… in the your_post_here element this time I load the output of a page of the blog called triqui-ajax. You’ll se later in this tutorial how to create it. This will work if the permalinks of your blog aren’t the default ones. Go to Settings -> Permalinks and select Day and name

I am also passing in POST a variable called id with the content of post_id variable (the post unique id)

Line 9: I added this line to prevent the browser to jump to the link… remember? I want to load the post in the same page.

Now it’s time to make some changes to index.php

This is how I modified it:

To tell the truth, I only added a line and changed a bit another one:

Line 10: This is the div that will contain the post, the one I change with jQuery (remember? lines 7 and 8 in the jQuery script)

Line 16: Here I changed the rel attribute to store the unique id of the post I want to load. I used it at line 6 in the jQuery script

And the template files do not need any other change.

Now it’s time to create a new page template with some code that will load the selected post.

In your template directory create a new php file, no matter its name… you can call it example.php and write this:

As you can see it’s almost the same code you can find in index.php at lines 15-24… because I just want to load a post in the same way the index file does. I just removed the anchor tag in the title, because I don’t want it to be clickable. And obviously I read the id value passed by the jQuery script at line 8

The only interesting lines are lines 2-4… yes, the comment… because this way I am giving the template page the name Triqui Ajax Post.

Now in your admin area create a new page, call it Triqui Ajax (do you remember the permalink url at line 8 in the jQuery script…) and select Triqui Ajax Post as template

And that’s it… you don’t need anything else, and the blog will work as in the video.

Enjoy

Rate this post: 1 Star2 Stars3 Stars4 Stars5 Stars (58 votes, average: 4.03 out of 5)
Loading ... Loading ...
Learn how to make a successful commercial Flash game from a real world example: get the fully commented source code of Globez, a Flash game played millions of times which generated a four figure income. Limited copies available.

Get it now
Be my fan on Facebook and follow me on Twitter! Exclusive content for my Facebook fans and Twitter followers

This post has 73 comments

  1. Loading WordPress Post with AJAX and JQuery | WPLover

    on April 2, 2010 at 2:24 pm

    [...] Loading WordPress Post with AJAX and JQuery [...]

  2. Ezequiel M.

    on April 3, 2010 at 12:37 am

    Nice, Thanks for share!

  3. Devon

    on April 3, 2010 at 10:09 pm

    Very cool article, thanks Emanuele!

  4. Loading WordPress posts with Ajax and jQuery – a real world example : Emanuele Feronato - italian geek and PROgrammer

    on April 6, 2010 at 11:28 pm

    [...] you are looking for a real world example made with Loading WordPress posts with Ajax and jQuery or you haven’t played LineBall yet, or you played it, you loved it and you want to know who [...]

  5. samuel jesse

    on July 4, 2010 at 7:42 am

    I couldn’t get this to work.

    On line 8 of the header code I had to replace:

    http://

    with:

    and it worked fine.

    Thanks for the post! Very helpful.

  6. samuel jesse

    on July 4, 2010 at 8:46 am

    That didn’t let me paste code sorry…

  7. Ben

    on July 6, 2010 at 8:42 pm

    Hi,

    This is a great tutorial. However I need to achieve something different. I have a list of categories that show initially in a certain page. When I click one category, the posts under that category should show via ajax in the same page. I already made this part working. So now that the posts under the category I selected are displayed, what I want to do is, when I click a post, the content of that post should also be loaded in the same page via ajax. So this should all happen without leaving the page that I was on from the start.

    Please help. Im really stucked.

    Thanks!

  8. Ben

    on July 7, 2010 at 3:27 pm

    I get it now. I was sure that loaded links arent working using the “.click”. I found out about the “.live” and its working now. So I used the original code you provided for the initial links that I have – which are the categories, then I added another function for the links that are freshly loaded – the posts under the selected category:

    $(“a.loaded-link”).live(‘click’, function(){
    var post_id = $(this).attr(“rel”)
    $(“#your_post_here”).html(“loading…”);
    $(“#your_post_here”).load(“http:///my-other-php-file/”,{id:post_id});
    return false;
    });

    Im now calling a different file that generates a different output.

  9. Marc

    on July 20, 2010 at 5:04 pm

    Damnit, What was it that you replaced it with @samuel?

    I have tried everything with this. It just doesn’t work.

    I AM using 3.0

    Please let readers know if this works on 3.0!

    Thanks so much for your help,
    Marc

  10. Steven

    on July 28, 2010 at 3:44 pm

    Nice technique! But the downside is that the url doesn’t change so you can’t use the back and forward buttons of your browser. I want to use jQuery Address together with you code. How do I begin?

  11. Maor

    on August 6, 2010 at 2:32 am

    Thank you very much for the post!

    Working great on WP3.0.1 as well.

  12. irengba

    on September 17, 2010 at 8:05 am

    Thanks for sharing.. Appreciate your work.

    I have one question-
    Is this possible with custom permalink? I just want SEO friendly url.

  13. trusktr

    on September 20, 2010 at 10:15 am

    Wow, this is very cool! I had to change line 8 around a little bit so that it reflected the URL of my blog in a subfolder.

    If yours doesn’t work, look at your outputted source code and the javascript should contain the path to/your/wordpress/install/ or it won’t work…

    By default, this code will just use your base domain and so it will only work as written on this page if you have your wordpress installed in the root folder. You need to change it to reflect your wordpress location.

  14. trusktr

    on September 20, 2010 at 11:16 am

    Check out what I’m working on using this method!
    http://atbskate.com/trusktr

    just click any of the squares….. next i’m going to add expanding of the chosen box…

  15. shag

    on September 21, 2010 at 10:46 pm

    killer post. This is almost exactly what I needed. One thing though, my next/previous post links aren’t working as I would have hoped. I’d like to load in the next/prev post via ajax into the #your_post_here div. Any thoughts on that?

    thanks in advance.

  16. Cool Magazine

    on September 22, 2010 at 12:59 am

    Trusktr, nice work. I need to work on ajax now as I have some plans for my site

  17. shag

    on September 24, 2010 at 8:48 pm

    nevermind. Once again I’m guilty of over-thinking things. I ended up creating a WP template file and page with just the info I wanted and opening that in a shadowbox where I can more easily use all the usual WP get_post functions etc., including the standard next/prev nav.

  18. Alireza

    on October 4, 2010 at 3:00 pm

    Hi thank you for this training is put your video files to better understand our training thanks

  19. trusktr

    on October 11, 2010 at 7:24 am

    Thanks! :D

    But for some reason it stopped working and I haven’t done anything! lol

    hmmmm…

  20. lonelicloud

    on October 18, 2010 at 1:00 pm

    It’s an amazing feature.
    But it seems that you are not using this in this site. Why?

  21. Richard

    on October 21, 2010 at 5:27 pm

    Love this feature, used it before.. but now have a problem I can’t get my head around.

    Developed site in a testing directory and it worked perfectly. Moved information to live directory (all on same server). Changed all necessary information (.htaccess, wordpress config, etc.) and WordPress is working cleanly. The javascript executes (triqui ajax loads) but it seems no post ID is being referred. I checked the variable in javascript and it is correct but $post is empty when checked in the template file. Entering a static value (in the template file) into the if variable works fine, content loads as it is supposed to. But for the life of me I can’t get the post id to get the info from the .load function.

    Any ideas?

  22. Daniel

    on November 5, 2010 at 12:29 pm

    Nice but didn’t work in all browsers until I found a missing “;” in the end of line 6 in header.

  23. Peter

    on November 5, 2010 at 1:54 pm

    Thanks for the tips. I was able to easily modify and play with it. Loaded posts by categories as archives without reloading the page. Awesome!

  24. Pablo

    on January 6, 2011 at 2:48 am

    Awesome!!! Thank you very much!! Nice explanation, Italian Genius!!

    Saludos desde Argentina!

  25. Mustafa

    on January 24, 2011 at 6:55 am

    Thanks a lot for this amazing trick !!

    Is this possible with default permalink?
    I just need SEO and I don’t want to loose them

  26. Lara

    on January 26, 2011 at 2:01 pm

    Hey,
    thanks for the tutorial. I try to implement the mechanism into my blog to prevent refreshing the background. I have two question concerning the coding:

    1. @ $(“h2 a”).click(function(){
    Can you just change “h2 a” into another div id used in the CSS template like $(“marker”)?

    2. If I wanted to use several on click conditions would I just add another block like the following into the script?

    $(“h1 a”).click(function(){
    var post_id = $(this).attr(“rel”)
    $(“#your_post_here”).html(“loading…”);
    $(“#your_post_here”).load(“http:///triqui-ajax/”,{id:post_id});
    return false;
    });

    Would be glad if you could help me!

  27. Gabriel

    on March 31, 2011 at 2:02 am

    Excellent post, it helped a lot.
    Thanks!

  28. Dot Red webdevelopment

    on April 22, 2011 at 9:59 pm

    Thanks m8 very useful post! I’m using it in combination with jQuery address.. works like a charm :)

  29. r3v

    on May 20, 2011 at 1:07 pm

    i try this tutorial but my side bar is lost, and i request ajax just for post , side bar and widget still in place.. thanks for advance…

  30. Floyd

    on May 30, 2011 at 4:00 am

    wow Thats cool, work like a charm for me… thanks bro :). By this you can integrate ajax with any WordPress functions. Thanks

  31. Jeffrey

    on June 1, 2011 at 10:32 am

    I almost got it to work, but It doesn’t recieve the right post ID. There for it doesn’t load the content.

  32. Alessandro Muraro

    on June 22, 2011 at 6:59 pm

    I’m about to try this solution, the only problem i think I might face beside technical issues, is that my irl will not be sharable through twitter and facebook. am i wrong? I mean, the permalinbk can be returned no problem, but my permalink won’t have the proper header/footer graphics because it is though to be a dinamically loaded content. Did you get around this?
    Or you just dont need such a feature?
    Alex

  33. Reddy

    on July 1, 2011 at 5:41 am

    Thank’s for agreat post …
    but how about SEO ?

  34. Gabriel Nechita

    on July 15, 2011 at 8:43 pm

    Hi there, thank you for this great tutorial, can I adapt this script to a button that also show a random post?

    I’m looking to create a great feature for a website and I really need to know if this can be done.

    The website has wordpress running, and I’ve already done the random post button, but I want the posts to load via ajax with no browser refresh.

    Can you please help me?

  35. Lawrence Dionisio

    on July 27, 2011 at 9:18 pm

    Hi,

    Very nice tutorial indeed and I have it working on my test site. I just have a minor (maybe major) tweak on it that I could not figure out.

    Is there a way to automatically load the first/recent post so that a content will always be present?

  36. Wordpress Elite

    on August 6, 2011 at 9:21 pm

    Nice tutorial! I just wonder how will this affect SEO of my WordPress blog. But thanks for this article, always a good stuff.

  37. Karen

    on August 23, 2011 at 10:44 am

    Hi I saw your blog a couple of days back and liked the articles listed.

    I work for CHW a website on web hosting and web designing. I would love to contribute something that your readers would like, possibly something about blogging.

    Would it be possible to guest post an article on your site?

    Regards,
    Karen

  38. YourTubeTheme

    on September 9, 2011 at 12:31 pm

    This Ajax tut was just what I was looking for, thank you! For ppl wondering about SEO, it will not have any negative affect, because you can still reach the post if you go to it through the post url.

  39. Antony

    on September 14, 2011 at 1:44 pm

    This tuto is perfect. Thanks for so much. Loving the community right now ;)

  40. Load Wordpress post content into DIV using AJAX | Gravity Layouts

    on September 23, 2011 at 10:57 am

    [...] far, I have gotten a slight idea from a great post (Loading WordPress posts with Ajax and jQuery) by Emanuele Feronato. He basically stores the post ID in the rel attribute of the clickable link [...]

  41. Navigate through Wordpress without refreshing

    on December 4, 2011 at 4:35 am

    [...] saw this page but, there is something [...]

  42. Victoria

    on January 25, 2012 at 6:56 pm

    I have been trying to implement this on a site I’m working on, but seem to be having some trouble. http://wordpress.org/support/topic/content-load-on-image-click?replies=4

    I’m confused by the usage of two pages, the index and another. I don’t wish to use this on my index page. That page is merely a splash. Any help would be great.

  43. deiv calviz

    on February 12, 2012 at 9:57 am

    Thanks for the tutorial! Is there a way for the post excerpts to load inline? Just like in facebook.

    There’s a plugin called AJAX Read More but it only works for the tag and not for excerpts.

  44. ColinR

    on March 6, 2012 at 2:16 am

    Fantastic post. Your clear and simple tutorial made this so easy to implement and modify. Thanks.

  45. Rodboc

    on March 7, 2012 at 8:51 pm

    Amazing, work for me :)

  46. Joe

    on March 8, 2012 at 10:37 am

    Nice!
    I am searching for a possibility in WordPress to (ajax)load content splitted by a wp_link_pages-function into the same div.
    Any ideas?

    Thanks!

  47. After seeing how to include jQuery Ajax calls in your WordPress blog, it’s time to load posts on the fly, without reloading the page. | Public Notes

    on April 1, 2012 at 1:29 am

    [...] Loading WordPress posts with Ajax and jQuery – Emanuele Feronato This entry was posted in Uncategorized by libanizi. Bookmark the permalink. [...]

  48. Wordpress ajax | Rainbowwhiteni

    on April 3, 2012 at 10:40 pm

    [...] Loading WordPress posts with Ajax and jQuery – Emanuele FeronatoApr 1, 2010 … you are looking for a real world example made with Loading WordPress posts with Ajax and jQuery or you haven’t played LineBall yet, or you … [...]

  49. Publish what you Learn II | inTOWN

    on April 8, 2012 at 6:19 pm

    [...] goal: Using this tutorial ( Loading WordPress posts with Ajax and JQuery) to load custom post types inline. I wanted to make [...]

  50. Publish what you Learn II | inTOWN

    on April 9, 2012 at 5:08 pm

    [...] doel: Deze tutorial ( Loading WordPress posts with Ajax and JQuery) leert hoe je posts online kan loaden, ik wil dat [...]

  51. Load Wordpress post content into DIV using AJAX

    on April 25, 2012 at 5:10 pm

    [...] far, I have gotten a slight idea from a great post (Loading WordPress posts with Ajax and jQuery) by Emanuele Feronato. He basically stores the post ID in the rel attribute of the clickable link [...]

  52. ¿Cómo implementar ajax de forma correcta en wordpress? | IDA Ltda

    on April 27, 2012 at 3:35 pm

    [...] que termina en un exit o die. También es bastante común encontrar trucos como los descritos en el este post, donde básicamente se crea una página de WordPress vacía que hace de intermediario entre el [...]

  53. Arpita

    on May 11, 2012 at 12:32 pm

    Simply Excellent post. Saved lots of hours for me….

  54. Load Wordpress post content into DIV using AJAX | Easy jQuery | Free Popular Tips Tricks Plugins API Javascript and Themes

    on May 21, 2012 at 7:41 am

    [...] far, I have gotten a slight idea from a great post (Loading WordPress posts with Ajax and jQuery) by Emanuele Feronato. He basically stores the post ID in the rel attribute of the clickable link [...]

  55. Arpita

    on May 22, 2012 at 3:09 am

    You should use /?page_id=x for your loading link, so even if your wordpress is installed on subdirectory, it will get the right URL.

    Arpita

  56. Arpita

    on May 22, 2012 at 3:11 am

    it is removing my php code but you should use bloginfo( ‘url’ );

  57. Reinaldo

    on June 3, 2012 at 10:42 am

    Ciao,
    Complimenti per il post, l’ho provato e funziona davvero molto bene!
    Volevo chiederti se mi potresti aiutare a capire come potrei fare per aprire la seconda pagina con tutti i post che voglio.
    per esempio:
    Tutti i post sono la stessa categoria, peró vorrei che all’indirizzo http://www.highlike.com.br la prima pagina mi mostri i 22 ultimi post random e alla fine, un pulsante “load more” per caricare gli altri 22 post (esclusi i 22 gia caricati di forma randon nel primo loop), soltanto voglio aggiungere sempre le pagine seguenti (non randon, ma per ordine di data del post)..
    Dici che é possibile una cosa del genere?

  58. Silvana

    on September 26, 2012 at 2:35 pm

    Grazie!

  59. ??? ???? | HateHunter

    on October 21, 2012 at 11:22 am

    [...] far, I have gotten a slight idea from a great post (Loading WordPress posts with Ajax and jQuery) by Emanuele Feronato. He basically stores the post ID in the rel attribute of the clickable link [...]

  60. Loading WordPress Posts With AJAX | Matthew Parashis - aspiring web developer

    on October 23, 2012 at 1:58 am

    [...] Check It Out Tweet !function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs"); BACK TO BLOG /* */ [...]

  61. Cafe 707

    on December 7, 2012 at 9:02 pm

    [...] Ajax Share this:TwitterFacebookLike this:LikeBe the first to like this. This entry was posted in Uncategorized by reportcafe. Bookmark the permalink. [...]

  62. Ram

    on January 9, 2013 at 12:53 pm

    hi really nice tutorial thanks ….:)

  63. cn arabic

    on March 4, 2013 at 1:56 pm

    Thank you sharing , i l look for a code ajax for load categories in the index.php because the home is verry slow .

  64. Francesco

    on March 15, 2013 at 3:31 pm

    Replaced http:// with and work!

  65. Gerardo Vidal

    on March 24, 2013 at 2:47 am

    Hi, Thanks for the code, it worked perfect to me, but I also have a problem, in the pages where i’m using ajax, the nav menu doesn’t appear (it is a theme nav menu, defined in the admin). And the problem is only with the footer menu, the one in the header (that is also defined in the admin) works.

    Any idea of how could I solve this?

    Thanks again.

  66. cartoon network arabic

    on July 21, 2013 at 3:43 pm

    [...] Ajax Share this:TwitterFacebookLike this:LikeBe the first to like this. This entry was posted in Uncategorized by reportcafe. Bookmark the permalink. [...]

  67. Bijay Yadav

    on August 28, 2013 at 6:50 am

    Thanks for the tutorial. Exactly what I was searching for. Will surely implement this in my next site. Thank you once again

  68. sameera

    on September 4, 2013 at 6:27 pm

    Thanks you very much. This saved my lots of time

  69. Daniel

    on September 18, 2013 at 4:57 pm

    I man,
    First of all, thanks a lot for this article.
    I used it on a website but I am having a really really slow response. Sometimes more than 1 second of delay after the click, even if i just load text…

  70. Anxhelo

    on September 24, 2013 at 4:05 pm

    hello there!
    First of all excellent script my friend!

    Now… It is any way to change and the url dynamically to make this script “SEO Friendly”?

    Thanks..!

  71. jaminsoft

    on January 25, 2014 at 2:04 pm

    Thank you very much for the post!

    Working great on WP3.0.1 as well.

  72. Roadmap Fortbildning av Javascript, Wordpress & Html5-history… | Note to helf

    on March 3, 2014 at 9:51 am

    […] using-ajax-with-wordpress-for-conditional-loading nostrongbeliefs.com loading-wordpress-posts-with-ajax-and-jquery emanueleferonato.com […]

  73. ¿Cómo implementar ajax de forma correcta en wordpress? -

    on May 27, 2014 at 7:36 pm

    […] que termina en un exit o die. También es bastante común encontrar trucos como los descritos en este post, donde básicamente se crea una página de WordPress vacía que hace de intermediario entre el […]

Thank you for the download!!

I hope you will find it useful and make something interesting out of it

To keep up to date with the blog, why don't you like my Facebook page and follow me on Twitter?

Want to learn more? Don't miss this:

Learn how to make a successful commercial Flash game from a real world example: get the fully commented source code of Globez, a Flash game played millions of times which generated a four figure income. Limited copies available.

Get it now

×