- WordPress Plugin Development Beginner's Guide
- Vladimir Prelovac
- 1503字
- 2025-03-31 06:47:52
Time for action – Use Ajax to dynamically retrieve feed posts
In order to work, Ajax usually needs to call a file on our server. This file is responsible for providing the response, and it is best that we put this Ajax functionality into a separate file.
- Create a file called
wp-live-blogroll-ajax.php
, implying that we want to use it for handling Ajax requests. - Add the code to include the necessary files, read the URL parameter passed to the script and call our function to deal with the URL:
<?php /* WP Live Blogroll Ajax script Part of a WP Live Blog Roll plugin */ require_once("../../../wp-config.php"); require_once(ABSPATH . WPINC . '/rss.php'); // fetch information from GET method $link_url = $_GET['link_url']; // return the result WPLiveRoll_Handle ajax($link_url);
- We will also need a utility function to get an excerpt from the text. We will use it to show only the first 20 words from the post:
function WPLiveRoll_GetExcerpt($text, $length = 20 ) { $text = strip_tags($text); $words = explode(' ', $text, $length + 1); if (count($words) > $length) { array_pop($words); array_push($words, '[...]'); $text = implode(' ', $words); } return $text; }
- We are going to add a function to parse the feed now. The function is similar to the first function we used at the beginning of the chapter, but it parses a number of posts and returns them in a formatted HTML. This function will return the result of our Ajax request.
function WPLiveRoll_HandleAjax($link_url) { // we will return final HTML code in this variable $result=''; // number of posts we are showing $number = 5; $link_url=trailingslashit($link_url); // pick the rss feed based on the site if (strstr($link_url,"blogspot")) { // blogspot blog $feed_url=$link_url."feeds/posts/default/"; } else if (strstr($link_url,"typepad")) { // typepad blog $feed_url=$link_url."atom.xml"; } else { // own domain or wordpress blog $feed_url=$link_url."feed/"; } // use WordPress to fetch the RSS feed $feedfile = fetch_rss($feed_url); // check if we got valid response if (is_array($feedfile->items ) && !empty($feedfile->items ) ) { // slice the number of items we need $feedfile->items = array_slice($feedfile->items, 0, $number); // create HTML out of posts $result.= '<ul>'; foreach($feedfile->items as $item ) { // fetch the information $item_title = $item['title']; $item_link = $item['link']; $item_description = WPLiveRoll_GetExcerpt($item['description']); // form result $result.= '<li><a class="lb_link" target="'.$link_target.'" href="'.$item_link.'" >'.$item_title.'</a><p class="lb_desc">'.$item_description.'</p></li>'; } $result.= '</ul>'; } else { // in case we were unable to parse the feed $result.= "No posts available."; } // return the HTML code die( $result ); } ?>
- In order to use Ajax we need to pass the url to our plugin to JavaScript. We will use
wp_localize_script
function to do that:function WPLiveRoll_ScriptsAction() { global $wp_live_blogroll_plugin_url; if (!is_admin()) { wp_enqueue_script('jquery'); wp_enqueue_script('wp_live_roll_script', $wp_live_blogroll_plugin_url.'/wp-live-blogroll.js', array('jquery')); // pass parameters to JavaScript wp_localize_script('wp_live_roll_script', 'LiverollSettings', array('plugin_url' => $wp_live_blogroll_plugin_url)); } }
- The moment has come. We will use simple Ajax request (
load
) to get a response from the script we have made. The response will be automatically loaded into our element as HTML content:$('#lb_popup').css({ left: mouseX + "px", top: mouseY + "px" }); // use load() method to make an Ajax request $('#lb_popup).load(LiverollSettings.plugin_url + '/wp-live-blogroll-ajax.php?link_url=' + this.href); // show it using a fadeIn function $('#lb_popup').fadeIn(300);
- We will comment out the text from the previous examples, and remove it from the
<div>
:// set the text we want to display // this.tip="Recent posts from " + this.href + " // will be displayed here..."; // create a new div and append it to the link $(this).append('<div id="lb_popup"></div>');
- We are ready to see the plugin in action. Let us upload all the files and test it. You should get a pop-up window showing five latest posts from the site:
Congratulations! You have created a Live Blogroll plugin using jQuery and Ajax!
What just happened?
The main difference here over our previous examples is in the use of Ajax in our JavaScript.
We have used the jQuery load()
function, which is the simplest way to call an external script and load the data into our page:
// use load() method to make an Ajax request
$('#lb_popup).load(LiverollSettings.plugin_url + '/wp-live-blogroll-ajax.php?link_url=' + this.href);
Notice how we reference lb_popup
when using the load()
function. This will load any output of our script into the lb_popup
element automatically.
Let's see now how our Ajax response script works.
First, we have created a new file wp-live-blogroll-ajax.php
to handle our Ajax requests. At the beginning of the file we referenced these includes:
require_once("../../../wp-config.php"); require_once(ABSPATH . WPINC . '/rss.php');
Notice how we included wp-config.php
. This is required because when our JavaScript calls the file, it will not be a part of WordPress code anymore, so we need to load all the WordPress functions and variables in order to use them. The easiest way is by including wp-config.php
, which in turn includes all the other necessary WordPress files.
Tip
Locating wp-config.php
like we did in our example is only a best guess at where the file is located and will work in most cases.
Since WordPress version 2.6, this file can be relocated anywhere in regards to plugin folder, so there is no certain way to tell its location. You are advised to check WordPress Codex for updated information on the topic.
Additionally, we included rss.php
for fetch_rss()
functionality.
Next, we read the link URL parameter that was passed to our file on the call from JavaScript. We use the GET
method as the Ajax request was using that.
// fetch information from GET method $link_url = $_GET['link_url'];
Next, we call the function for handling the feed:
// return the result WPLiveRoll_HandleAjax($link_url);
This function uses an approach similar to the one we have already described. The difference begins with the feed processing part.
We want to process a number of posts (five by default); so we slice that number from the array of feed
items:
// slice the number of items we need $feedfile->items = array_slice($feedfile->items, 0, $number);
Next, we process each feed item and extract the title, link and description:
// create HTML out of posts $result.= '<div><ul>'; foreach($feedfile->items as $item ) { // fetch the information $item_title = $item['title']; $item_link = $item['link']; $item_description = WPLiveRoll_GetExcerpt($item['description']);
We prepare the code using a HTML list with this information:
// form result $result.= '<li><a target="'.$link_target.'" href="'.$item_link.'" >'.$item_title.'</a><p>'.$item_description.'</p></li>';
In case we had a problem processing the feed, we will return a message:
$result.= '</ul></div>'; } else { // in case we were unable to parse the feed $result.= "No posts available"; }
Finally, we return the result using the die()
function to end our Ajax response script:
// return the HTML code die( $result ); }
Using JavaScript with WordPress
The main difference between JavaScript and PHP is that JavaScript is client based (it executes in the user's browser) whereas PHP is server based (it executes on the remote server). This means JavaScript is good at handling user actions (clicking, moving the mouse, and so on) while PHP is good at dealing with server variables, database and other things happening remotely.
This also means that we need to find a way to connect the two. Most of the time, we need a way to pass variables from PHP to JavaScript and user actions from JavaScript to PHP.
Parsing parameters using wp_localize_script
WordPress provides wp_localize_script
function which is an elegant way to pass the parameters to your JavaScript.
wp_localize_script('wp_live_roll_script', 'LiverollSettings', array('plugin_url' => $wp_live_blogroll_plugin_url));
First parameter is our script's name followed by the name of JavaScript object that will hold the settings. Next you can specify the array of parameters.
These parameters will be available in JavaScript and can be accessed as LiverollSettings.plugin_url
Ajax and WordPress
As we have seen, integrating Ajax functionality with WordPress is relatively easy. The basic Ajax flow chart looks generally like this:
- The user does something on the page (like clicking or moving the mouse) and the JavaScript code is triggered. It then creates and calls another file on the server (Ajax response script).
- Ajax response script will process the request based on our input parameters and return the output back to the browser.
- The returned information is then processed and displayed by the JavaScript in the browser.
You can see examples of Ajax in the administration panel such as auto-saving of posts, moderating of comments or managing of your blogroll and categories.
For handling Ajax calls happening in the administration panel, there is another simple alternative.
The way this works is that we create a function for handling the Ajax request and assign it to the wp_ajax
hook by extending it with the desired name, as shown here:
add_action('wp_ajax_my_function', 'my_function' );
Step two, we make an Ajax call to admin-ajax.php
and send the name as a parameter. The jQuery call would look something like this:
$('#info').load('admin-ajax.php?action=my_function');
The most obvious benefit of this approach is that the Ajax handling function can freely be a part of your main script, and you can easily change it by assigning another function to the wp_Ajax
action.
jQuery.ajax method
When we want more control, especially error handling, we will use the more advanced Ajax()
function.
This function accepts several parameters of interest:
type
: The type of request to make ('POST
' or 'GET
'); the default isGET
.url
: The URL to be requestedtimeout
: A set of local timeouts in miliseconds (ms) for the requestsuccess
: A function to be called if the request succeedserror
: A function to be called if the request failsasync
: By default, all requests are sent asynchronously. If you need synchronous requests, set this option to false. Synchronous requests may temporarily lock the browser, until the request is finished
Let's use this more advanced function in our JavaScript now.