Dynamically Load WordPress Posts with jQuery
Jun 25, 2011 | In jQuery, Tutorials, Wordpress |Today, I will show you how to dynamically load wordpress posts with jQuery’s .load function. Dynamically loading posts has many advantages and disadvantages over simply linking to the post page. It makes the page more dynamic, and decreases the wait time between the post preview and the actual post. However, this technique does have some major disadvantages. It is less SEO-friendly, and the posts that are loaded cannot be bookmarked unless you have some sort of deep linking plugin. An example of this would be Asual’s jQuery Address plugin.
Now, to the tutorial.
First, go to your theme’s index page and make a div that will hold the new post.
<div id="post"></div>
Still in your index page, go to your post loop section and add this code to your post links.
rel="<?php the_ID(); ?>"
This isn’t that important, but it does give us extra information if we ever need it.
It doesn’t matter where this div goes, as long as it is somewhere on the index page. Once you have the div in your theme’s index.php file, go to your single template and delete everything except for the post itself – this is what will display in our “post” div. It should look something like this:
<div id="post_container"> <h1 id="post_header"><a href=""><?php the_title(); ?></a></h1> <div id="post_date"><?php the_time('l, F jS, Y') ?></div> <div id="post_text"><?php the_content(); ?></div> </div>
Now, go into your header.php file and write this code in a script tag.
$(document).ready(function(){ $.ajaxSetup({cache:false}); $("a").click(function(){ var post_url = $(this).attr("href"); var post_id = $(this).attr("rel"); $("#post").html("loading..."); $("#post").load(post_url); window.location.hash = post_id; return false; }); });
Now, step by step:
1.When the document is ready, set jquery’s cache to false.
2.Then, add an click event handler to every link on the page. Change the “a” to wherever your post links are.
3.Put the text “loading” into the post div.
4.Load the post into the post div.
5.Set the url to show the post id, change this to whatever you want.
6.Make the link not actually work.