And because we did it all with Java Script, we know our plugin degrades gracefully (Because if the Java Script isn’t loaded, no changes will be made to the page).
next_posts() is a built-in Word Press function that will return the URL we need. The second value, ‘pbd_alp’, is the name we will use in our Java Script later on. If you view the HTML source of your webpage later, you’ll see something like this right before your Java Script file is loaded: (pbd_alp was the second value we entered in wp_localize_script(), remember? The important thing to remember is that our numbers have been sent over as strings, so we use Java Script’s parse Int() function to convert them back to numbers. Most themes already have navigation to move between pages, in the form of Older Posts/Newer Posts links.
We want to replace that with our AJAX button, so our first step will be to remove those navigation links, and insert our button instead. The first is an empty div, which we will later use to insert our posts into.
The second is the button itself (A regular HTML link), wrapped up in a paragraph. The result of the code above is that our button is now in place, though it won’t do anything yet.
* Version: 0.1 * Author: Pro Blog Design * Author URI: * License: GPLv2 */ variable, which we’ll use in the next step. This is a broad brush to make sure our code runs on the homepage, tag pages, search pages etc. if you don’t want the code included on your homepage.
We then use wp_enqueue_script() and wp_enqueue_style() to tell Word Press about our two files (As well as the fact that we will be using j Query).
Now, we need to pass some values to our script, namely: We will use the wp_localize_script() function to calculate each of these values in PHP, and then print them into the webpage so that our script can access them later (Hat tip to Professional Word Press Plugin Development for introducing me to this great function!
) variable will store the page we are currently on (The whole point of our plugin is to ensure people never load a second page, but it doesn’t hurt to make sure).
Today, we’re going to replace the standard “Older Posts” links on your blog.
Our plugin will create a button to instantly load the next page of posts, without reloading the page (Similar to what Twitter used to do at the bottom of profiles) Click here to load the demo site and see the final project in action.
You can also download the completed files as a plugin here (Just upload and activate it). Our plugin is going to have several features: There will be 3 files in this plugin (One PHP, one CSS, one JS).
For good practice, we’ll keep the CSS and Java Script in their own folders. Now let’s start by putting the necessities at the top of our /** * Plugin Name: PBD AJAX Load Posts * Plugin URI: * Description: Load the next page of posts with AJAX. It means that on any page that isn’t an individual post or Page, we are going to run this code.