Академический Документы
Профессиональный Документы
Культура Документы
com/)
Ajax has rapidly become a popular web technology, you’ll nd it used on most websites. The key feature of Ajax is it can
manage database operations without reloading the web page. This means, you can fetch data from the database and display
it on the front-end without needing to refresh the page.
It’s a fast and smooth way for displaying content, and as a result Ajax is now used in many various ways on a website, such as
submitting blog comments, liking posts and uploading les. You can even make your website completely Ajaxi ed, so that
each page of your site will load asynchronously.
Given the popularity of Ajax, most of the leading CMS platforms use it within their architecture. WordPress is no different.
Actually WordPress employs Ajax in a very robust and easy way, and today I will show you just how you can use Ajax in
WordPress with a real world example. Before we get started, I’ve assumed you have some knowledge of jQuery Ajax methods
and WordPress hooks, as we will need both!
If you’re looking for some basic WordPress development tutorials, check out WordPress Plugin Development for Beginners
(https://www.sitepoint.com/wordpress-plugin-development-beginners/).
1 The URL of the WordPress admin-ajax.php le, where the data to be sent for processing.
2 The Ajax action hook called wp_ajax_. You need to hook a custom function into it which will be executed during the Ajax
call.
Let’s create a plugin to understand how this works. Let’s say we want to develop a plugin that will allow users to save their
favorite blog posts in a certain area so that they can read them later. This feature is useful for magazine style blogs which
provide lots of content daily. It will allow logged in users to save interesting posts in a members only area, so that they can
come back and read them later.
( )
So our (https://www.sitepoint.com/)
‘Read Me Later’ plugin will do several things:
First, we will make a link at the bottom of every blog post content.
OFFER ENDS IN 07 HRS 21 MINS 55 SECS
When a user clicks to the link, the link’s post’s ID will save in the usermeta database table without page reload.
Finally, we will create a widget
Get Allto show
Our Books blog postsFor
And Courses based
50% Offon the posts IDs saved in the database.
(Https://Www.Sitepoint.Com/Premium/L/Join?
Ref_source=Sitepoint&Ref_medium=Noticebar&Ref_campaign=2-Years-For-1)
Then we need to create four les, which I have listed below with the proper le extensions:
read-me-later.php
widget.php
read-me-later.js
read-me-later. css
The rst two les will directly go in the main plugin folder. The js and css les will be put in the js and the css folders,
respectively.
Now we’ll populate the read-me-later.php le. Including the plugin header:
/**
* Plugin Name: Read Me Later
* Plugin URI: https://github.com/iamsayed/read-me-later
* Description: This plugin allow you to add blog posts in read me later lists using Ajax
* Version: 1.0.0
* Author: Sayed Rahman
* Author URI: https://github.com/iamsayed/
* License: GPL3
*/
This code is important as it’s used to identify that’s it’s a plugin to WordPress. After the above code, we’ll create our main
plugin class called ReadMeLater:
class ReadMeLater {}
( )
(https://www.sitepoint.com/)
/*
* Action hooks
*/
public function run() {
OFFER ENDS IN 07 HRS 21 MINS 55 SECS
// Enqueue plugin styles and scripts
Get All Our Books And Courses For 50% Off (Https://Www.Sitepoint.Com/Premium/L/Join?
add_action( ‘plugins_loaded’, array( $this, 'enqueue_rml_scripts' ) );
Ref_source=Sitepoint&Ref_medium=Noticebar&Ref_campaign=2-Years-For-1)
add_action( ‘plugins_loaded’, array( $this, 'enqueue_rml_styles' ) );
}
/**
* Register plugin styles and scripts
*/
public function register_rml_scripts() {
wp_register_script( 'rml-script', plugins_url( 'js/read-me-later.js', __FILE__ ), array('jquery'), null,
true );
wp_register_style( 'rml-style', plugins_url( 'css/read-me-later.css' ) );
}
/**
* Enqueues plugin-specific scripts.
*/
public function enqueue_rml_scripts() {
wp_enqueue_script( 'rml-script' );
}
/**
* Enqueues plugin-specific styles.
*/
public function enqueue_rml_styles() {
wp_enqueue_style( 'rml-style' );
}
The code is fairly self explanatory. Here, we’ve created a public method called register_rml_scripts(). Inside this
method, we have registered our read-me-later.js and read-me-later.css les using proper WordPress functions.
The next two methods enqueue_rml_scripts() and enqueue_rml_styles() are used to enqueue our JavaScript and
stylesheet. We’ve also created a run method, which will contain all of our action (and lter) hooks.
If you’re new to WordPress, you can check out Enqueuing Scripts and Styles in WordPress
(https://www.sitepoint.com/enqueuing-scripts-styles-wordpress/) by Younes Ra e, or search the WordPress codex to learn
how to register and enqueue JavaScript and CSS les properly.
( )
(https://www.sitepoint.com/)
/**
* Adds a read me later button at the bottom of each post excerpt that allows logged in users to save those
posts in their read me later list.
*
OFFER ENDS IN 07 HRS 21 MINS 55 SECS
* @param string $content
Get All Our Books And Courses For 50% Off (Https://Www.Sitepoint.Com/Premium/L/Join?
* @returns string
Ref_source=Sitepoint&Ref_medium=Noticebar&Ref_campaign=2-Years-For-1)
*/
public function rml_button( $content ) {
// Show read me later link only when the user is logged in
if( is_user_logged_in() && get_post_type() == post ) {
$html .= '<a href="#" class="rml_bttn" data-id="' . get_the_id() . '">Read Me Later</a>';
$content .= $html;
}
return $content;
}
Here, we checked both if the user is logged in and if the post type is a post. After checking this we create the link. Notice that
we use the HTML5 data attribute to contain the blog post’s ID which can be retrieved with the function get_the_id(). Since
the link will be placed inside the post loop, this is the exact function we need.
To place the link under the each blog post, add the code bellow inside the run method:
This will lter the post excerpt and place the link inside the loop. Now when you’re logging in to your WordPress website and
you browse your home page (or the page showing your posts), you’ll see the ‘Read Me Later’ link at the bottom of every post.
So, if we write rml_obj.ajax_url , it will output the value of admin_url('admin-ajax.php'), in other words, the URL
of the admin-ajax.php le. We’ll use it in the JavaScript part.
Don’t forget to place the above code inside our enqueue_rml_scripts() method that we created earlier.
( )
(https://www.sitepoint.com/)
jQuery(document).ready( function(){
jQuery('#content').on('click', 'a.rml_bttn', function(e) {
e.preventDefault();
var rml_post_id = jQuery(this).data( 07 HRS 21 MINS 55 SECS
OFFER ENDS IN
'id' );
jQuery.ajax({
Get All Our Books And Courses For 50% Off (Https://Www.Sitepoint.Com/Premium/L/Join?
url : readmelater_ajax.ajax_url,
Ref_source=Sitepoint&Ref_medium=Noticebar&Ref_campaign=2-Years-For-1)
type : 'post',
data : {
action : 'read_me_later',
post_id : rml_post_id
},
success : function( response ) {
jQuery('.rml_contents').html(response);
}
});
jQuery(this).hide();
});
});
In the above code we’ve created a function that will be called when the user clicks the ‘Read Me Later’ link. Inside this function
we grab the post ID using data method and store it into the ‘rml_post_id’ variable. After that, we made our Ajax call using
jQuery ‘$.ajax()’ method. This method takes several properties as we mentioned earlier in this article. Let me explain them one
by one.
url contains the URL of the admin-ajax.php le. Remember how we de ned rml_obj.ajax_url in the previous step?
That’s how we use the URL here. Our Ajax request will be sent there for processing.
type indicates whether the request will send using HTTP ‘$_GET[]’ or ‘$_POST[]’ method. We use ‘$_POST[]’
method here, as we set it as post.
data contains the data we want to send with the Ajax call. Here, our data is an object as key-value pairs. post_id contains
the post ID, and action contains read_me_later which is the su x of wp_ajax_ hook. We will de ne the Ajax action
hook and its callback function in the next step.
The last one is success which is contains an anonymous function. It will re when the Ajax call has been nished.
Make sure your read me later link is wrapped with a div tag with a #content id attribute otherwise the jQuery won’t
work.
Now we need to remove the Read Me Later link right after the user clicks on it, so that the user can’t save a post twice. To
achieve this, we added the following code after the jQuery.ajax() method:
jQuery(this).hide();
This will remove the ‘Read Me Later’ link when the user clicks on it.
So far we’ve created the Read Me Later link and connected it with Ajax. But the link doesn’t do anything yet, because we
haven’t written any server side code to process the Ajax request. When the user clicks the link we need to save that post ID in
the database and then display posts in the frontend based on the database information.
To accomplish this kind of server side processing, WordPress gives us two action hooks, wp_ajax_my_action and
wp_ajax_nopriv_my_action . The rst one will work only for logged in users, and the second will be useful when users
aren’t logged in. Because our example plugin is designed for logged in users only, we will use the rst one. Note that
( )
(https://www.sitepoint.com/)
my_action is the su x of the wp_ajax_ hook and you can name it as you wish.
The only thing you need to be careful of with the above code is to make sure that your Ajax hook su x matches the value of
the action property of your jQuery.ajax() method (seen in the previous step). You may notice that we give the same
name to the callback function so that we can remember it easily. Now we’ll de ne our callback function:
if( $value ) {
$echo = $value;
array_push( $echo, $rml_post_id );
}
else {
$echo = array( $rml_post_id );
}
The above code should be placed inside our main plugin class. Let me explain what I did here.
First, we stored the post ID in the $rml_post_id variable. Then we declared an empty array called $echo.
After that, we check that there’s a eld with the key rml_post_ids in the usermeta table in our database. If there is a row,
we grab the meta value using get_user_meta() WordPress function and store it in $value.
Again, we check whether the $value exists or not. If true, we store it in the previously declared $echo array. Then we push
the value of $rml_post_id inside the array using the array_push() function. If there is no $value, then we simply store
$rml_post_id in $echo.
update_user_meta() is responsible for updating (or creating, if the eld has not yet been created) meta eld with the data
stored in $echo.
Finally, we store the recently populated meta eld using get_user_meta() in $ids as an array.
Now we’ve got the user chosen post IDs, we need to display those posts. Add the following code:
( )
(https://www.sitepoint.com/)
// Query read me later posts
$args = array(
'post_type' => 'post',
'orderby' => 'DESC',
OFFER ENDS IN 07 HRS 21 MINS 55 SECS
'posts_per_page' => -1,
Get All Our Books And Courses For 50% Off (Https://Www.Sitepoint.Com/Premium/L/Join?
'numberposts' => -1,
Ref_source=Sitepoint&Ref_medium=Noticebar&Ref_campaign=2-Years-For-1)
'post__in' => $ids
);
Here, we use the WordPress get_posts() function to get all the posts based on the user’s choice. The only required
parameter here is post__in which contains the array of post IDs. Lastly, we use die() so that our Ajax content will echo
properly.
( )
(https://www.sitepoint.com/)
/**
* Hook into wp_ajax_ to save post ids, then display those posts using get_posts() function
*/
public function read_me_later() {
OFFER ENDS IN 07 HRS 21 MINS 55 SECS
Get All Our Books And Courses For 50% Off (Https://Www.Sitepoint.Com/Premium/L/Join?
$rml_post_id = $_POST['post_id'];
Ref_source=Sitepoint&Ref_medium=Noticebar&Ref_campaign=2-Years-For-1)
$echo = array();
if( $value ) {
$echo = $value;
array_push( $echo, $rml_post_id );
}
else {
$echo = array( $rml_post_id );
}
( )
(https://www.sitepoint.com/)
class RML_Widget extends WP_Widget {}
Create the __construct() magic method inside the class to initialize our widget:
OFFER ENDS IN 07 HRS 21 MINS 55 SECS
Get All Our Books And Courses For 50% Off (Https://Www.Sitepoint.Com/Premium/L/Join?
function __construct() {
Ref_source=Sitepoint&Ref_medium=Noticebar&Ref_campaign=2-Years-For-1)
parent::__construct(
'rml_widget', // Base ID
__( 'Read Me Later', 'text_domain' ), // Name
array( 'classname' => 'rml_widgt', 'description' => __( 'Read Me Later widget for displaying saved
posts', 'text_domain' ), ) // Args
);
}
Here we’ve set a name and description to the widget which will display in the dashboard widget section.
A backend widget form will be created by the form() method, like this:
As you can see, our form consists of a text eld that contains the title of the widget. We assign our title in the $title
variable. The get_field_id() and the get_field_name() gives our text eld an unique ID and name, respectively.
The update() method is responsible for sanitizing and updating the user input value.
return $instance;
}
1 The $new_instance contains the value entered by a user using the backend form we’ve created by the form() method.
2 The $old_instance is opposite, it contains the previous value.
Now we’ll create the widget() method which will display the ‘Read Me Later’ posts in the frontend.
( )
(https://www.sitepoint.com/)
public function widget( $args, $instance ) {
$title = apply_filters( 'widget_title', $instance['title'] );
echo $args['before_widget'];
if ( ! empty( $title ) ) {
OFFER ENDS IN 07 HRS 21 MINS 55 SECS
echo $args['before_title'] . $title . $args['after_title'];
Get All Our Books And Courses For 50% Off (Https://Www.Sitepoint.Com/Premium/L/Join?
}
Ref_source=Sitepoint&Ref_medium=Noticebar&Ref_campaign=2-Years-For-1)
$args = array(
'post_type' => 'post',
'orderby' => 'DESC',
'posts_per_page' => -1,
'numberposts' => -1,
'post__in' => $ids
);
echo '</div>';
echo $args['after_widget'];
}
Here we use the get_posts() function to display posts. Pretty much same as read_me_later() method.
Don’t forget to include the widget.php le by adding the following code at the top of the read-me-later.php le:
First, we will create a nonce using the wp_create_nonce() method and pass it from JavaScript. To achieve this, use the
code from the enqueue_rml_scripts() method:
( )
(https://www.sitepoint.com/)
wp_localize_script( 'read-me-later', 'readmelater_ajax', array( 'ajax_url' => admin_url('admin-ajax.php') ) );
Now we can access the nonce value from our JavaScript using readmelater_ajax.check_nonce. Add a security
property in the jQuery.ajax() method in your JavaScript le, like below:
security : readmelater_ajax.check_nonce
jQuery(document).ready( function(){
jQuery.ajax({
url : readmelater_ajax.ajax_url,
type : 'post',
data : {
action : 'read_me_later',
security : readmelater_ajax.check_nonce,
post_id : rml_post_id
},
success : function( response ) {
jQuery('.rml_contents').html(response);
}
});
jQuery(this).hide();
});
});
Finally, we need to check the nonce in our Ajax callback. We will use the check_ajax_referer() function to achieve this.
Add the following code at the beginning of the read_me_later() method we created earlier:
This takes two arguments. The rst is the key we created using wp_create_nonce(). The second is the security
property we passed from the JavaScript.
If the nonce is incorrect or not set, the Ajax call will die. This way our script will block invalid Ajax requests.
Conclusion
In this tutorial, we made a system where users will be able to save their favorite posts in a list and read them later. You can
always add more features to it, such as creating a different page to show all saved posts, ability to add pages to the list or to
add posts from custom post types for example. You can even make a dashboard settings page to con gure all of the options.
It’s up to you and the kind of features you want to create for your users.
( )
As you(https://www.sitepoint.com/)
can see, it’s easy to use Ajax in WordPress. It may be daunting for the rst time, but once you understand how to do
this, it works and looks great. WordPress Hooks are everywhere and they make your life easier. I hope you’ve picked up some
useful techniques from this tutorial, now play with Ajax and make things that you love!
OFFER ENDS IN 07 HRS 21 MINS 55 SECS
Get All Our Books And Courses For 50% Off (Https://Www.Sitepoint.Com/Premium/L/Join?
Meet the author Ref_source=Sitepoint&Ref_medium=Noticebar&Ref_campaign=2-Years-For-1)
I’m a web developer, writer and web enthusiast. My primary focus is on WordPress, as I love to make themes, plugins and custom WordPress websites.
Usually I like to develop and then share my experience.
HOW TO OPTIMIZE CSS ANGULAR ROUTER: AN RUBYMINE: CODE 24 PRODUCTIVITY TOOLS 23 DEVELOPMENT TOOLS 11 PRODUCTIVITY TOOLS HOW TO BUILD A
AND JS FOR FASTER SITE… INTRODUCTION TO… INSIGHT FOR RUBY AND… TO HELP YOU WITH YO… FOR BOOSTING WEBSIT… TO HELP WEB… APP THAT WORKS
Mats Svensson Cecily Dantam Sid John Camacho User_PCS David Putnam Hugo Hyz
1d 8 Sep 12 Jan 18 Dec 14 Dec 9 Sep 7 Dec
There are some bad This was exactly the Thank you so much How is a wordpress Very informative and I had expected to see Awesome conte
advice here, that will… tutorial I was looking… for this post... theme a productivity… veryhelpful list of… basecamp(.com) in… looking to trans
( )
(https://www.sitepoint.com/)
Conversation (8)
Lay
·28 Oct, 2016
Nice tutorial.
Reply · Share ·
Denis Žoljom
·7 Nov, 2016
Nice tutorial. One thing though, you should escape your output, and sanitize inputs. In your ajax function, rst check if the $_POST variables are set,
verify nonce and check if the necessary $_POST variables are not empty. Then you can proceed with function execution.
Also
numberposts is deprecated, so you can remove it, and don't use posts_per_page => -1, since that can slow your query down a lot (you're querying
all the posts). Depending on how many posts you have, just enter a very large number.
Reply · Share · 1 Like ·
Furqan
·13 Nov, 2016
Good tutorial for beginners but still lack information from security perspective...
Reply · Share ·
Nadeem Akram
·7 Dec, 2016
Nice tutorial, thank u.
Reply · Share ·
Michael Sperber
·
So8how
Dec, 2016
is the ReadMeLater class get instantiated? All the code is inside this class, I think it's never called? e.g. i see no css or js injected in the page.
Reply · Share · 1 Like ·
surja
· 19 Dec, 2016
Thank you for the tutorial. I installed the plugin from the github page, activated it. Then added the "Read Me Later" widget in the sidebar. But when
I click the Read Me Later links below the excepts of the posts, no posts are saved and shown in the widgets area. How do I go about debugging the
problem?
Reply · Share ·
Versioning (/versioning/) Press Room (/press/) FAQ (https://sitepoint.zendesk.com/hc/en-us) Privacy Policy (/legals/#privacy)
References (/html-css/css/)
( )
(https://www.sitepoint.com/)
Connect
(https://plus.google.com/+sitepoint)
Get All Our Books And Courses For 50% Off (Https://Www.Sitepoint.Com/Premium/L/Join?
© 2000 – 2018 SitePoint Pty. Ltd.
Ref_source=Sitepoint&Ref_medium=Noticebar&Ref_campaign=2-Years-For-1)