Skip to Main Content

Javascript on WordPress: AJAX use case

Divi: the easiest WordPress theme to use

Divi: The best WordPress theme of all time!

With over 901.000 downloads, Divi is the most popular WordPress theme in the world. It is complete, easy to use and comes with more than 62 free templates. [Recommended]

Ajax, or Asynchronous Javascript and XML, is used to communicate with server-side scripts and allows you to load dynamic content without having to reload the page.

Say, for example, that you are building a website for a local charity and you want to encourage a positive atmosphere. You can add a button labeled "Show some love! »With a counter on the home page and, thanks to AJAX, every time the button is activated (clicked by a visitor), the counter increments without reloading the page.

This is the example that we will build in this tutorial.

In this tutorial, you will learn more about what AJAX is, how it can be used, and how to create awesome features with it on WordPress.

Let's start.

The basics of AJAX

  • The AJAX feed usually follows the following steps:
  • Initiate an AJAX call due to user action
  • Receive and process the request on the server
  • Capture the response and perform all the necessary actions via JavaScript
  • Setting up a new theme environment

Let's put this into practice on WordPress. Our first example displays a simple popup containing the number of comments for an article when we click on the title. We will use a child theme based on the " Twenty Sixteen From WordPress.

Here's what you need to do:

Create a new folder in the Themes directory in your WordPress installation in " wp-content "And name it" ajax-test ", create the two files Required by WordPress, to know " functions.php "," Styles.css "and add a new file called" script.js ". Add the following code to the header of your CSS stylesheet (style.css).

/ * Theme Name: Ajax Test Theme URI: Description: A theme for testing our AJAX knowledge Author: Daniel Pataki Author URI: Template: twentysixteen Version: 1.0.0 License : GNU General Public License v2 or later License URI: * /

The parent theme's stylesheet must be loaded by the child theme. In the past this was done by importing the CSS file into the child theme, but the recommended way to do this is to use "enqueueing". Remember, we showed you how to use this feature.

So let's add the parent style sheet and our JavaScript file directly:

Add_action ('wp_enqueue_scripts', 'ajax_test_scripts'); function ajax_test_scripts () {wp_enqueue_style ('parent-style', get_template_directory_uri (). '/style.css'); wp_enqueue_script ('ajax-test-scripts', get_stylesheet_directory_uri (). '/scripts.js', array ('jquery'), '1.0.0', true); }

If you feel like you have the energy to take it a step further, find a nice image, crop it to 880px by 660px and place it in the child's theme folder, then rename it " screenshot.png ". It will appear in the appearance section, when you want to activate the theme.

ajax WordPress example theme

Since this child theme is based on “ Twenty Sixteen And that we have not changed anything (yet!), The site should look exactly like a classic theme with the theme " Twenty Sixteen ».

Adding a button

To begin, we will add the button " Show a little love! ". A great place to display it would be on the sidebar for themed articles.

After some research, it turns out that the sidebar is created by a function named " twentysixteen_entry_meta () »Which resides in the directory« inc / template-tags.php ».

Easily create your website with Elementor

Elementor allows you to easily create any website design with a professional look. Stop paying expensive for what you can do yourself. [Free]

This function is " connectable Which means we can modify it by defining it in our own functions.php file. The first step is to copy and paste the entire function into our own functions.php file:

function twentysixteen_entry_meta () {if ('post' === get_post_type ()) {$ author_avatar_size = apply_filters ('twentysixteen_author_avatar_size', 49); printf (' % 1 $ s % 2 $ s % 3 $ s ', get_avatar (get_the_author_meta ('user_email'), $ author_avatar_size), _x ('Author', 'Used before post author name.', 'twentysixteen'), esc_url (get_author_posts_url (get_the_author_meta ('ID'))), get_the_author ()); } if (in_array (get_post_type (), array ('post', 'attachment'))) {twentysixteen_entry_date (); } $ format = get_post_format (); if (current_theme_supports ('post-formats', $ format)) {printf (' % 4 $ s % 1 $ s ', sprintf (' % s ', _x (' Format ',' Used before post format. ',' twentysixteen ')), esc_url (get_post_format_link ($ format)), get_post_format_string ($ format)); } if ('post' === get_post_type ()) {twentysixteen_entry_taxonomies (); } if (! is_singular () &&! post_password_required () && (comments_open () || get_comments_number ())) {echo ' '; comments_popup_link (sprintf (__ ('Leave a comment on% s ', 'twentysixteen'), get_the_title ())); echo ' '; }}

Let's add our key to the bottom of all the metadata:

$ love = get_post_meta (get_the_ID (), 'show_some_love', true); $ love = (empty ($ love))? 0: $ love; echo ' '. $ love. ' ';
Let's explain all this code:

The first line retrieves the number of loves that the article has received. In some cases, this data will not exist, in other words when the button has not yet been clicked. For this reason, we use

the second line in the code to set the value to 0 if the value is empty.

The third line delivers the button, which consists of a span containing a picture and the number of loves. I left the source of the image blank because I want to use an SVG in there. You can use a base64 encoded SVG to create an image line. This saves you from making requests and will make your website more efficient.

I used this little free image available this link. Copy and paste the code you receive into the image source like this:

$love = get_post_meta( get_the_ID(), 'show_some_love', true );
$love = ( empty( $love ) ) ? 0 : $love;
echo '<span class="love-button"> <img width="28" src="data:image/svg+xml;base64,PD94bWwgdmVyc2lvbj0iMS4wIiA/PjxzdmcgaGVpZ2h0PSI0MHB4IiBpZD0iTGF5ZXJfMSIgc3R5bGU9ImVuYWJsZS1iYWNrZ3JvdW5kOm5ldyAwIDAgNDAgNDA7IiB2ZXJzaW9uPSIxLjEiIHZpZXdCb3g9IjAgMCA0MCA0MCIgd2lkdGg9IjQwcHgiIHhtbDpzcGFjZT0icHJlc2VydmUiIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgeG1sbnM6eGxpbms9Imh0dHA6Ly93d3cudzMub3JnLzE5OTkveGxpbmsiPjxwYXRoIGQ9Ik0xOS45NzkwMDAxLDkuMTk1MzAwMSAgQzI1LjYzOTIwMDItMS44ODY3LDM4LjUxMTY5OTcsMy4zOTU5OTk5LDM3Ljk0OTE5OTcsMTMuMzAyN0MzNy4zNjM4LDIzLjYxNjE5OTUsMjIuODc0NTAwMywyNy4xNzM3OTk1LDE5Ljk3OTAwMDEsMzQuOTgxODk5MyAgQzE3LjA4MzAwMDIsMjYuOTc5MDAwMSwyLjc4OTU5OTksMjMuODExNTAwNSwyLjAwODMwMDEsMTMuMzAyN0MxLjI3MzksMy40MDc3MDAxLDE0LjkzNTk5OTktMS45MzEyLDE5Ljk3OTAwMDEsOS4xOTUzMDAxeiIgc3R5bGU9ImZpbGwtcnVsZTpldmVub2RkO2NsaXAtcnVsZTpldmVub2RkO2ZpbGw6I0ZGNTk0RjsiLz48L3N2Zz4="><span class="number">' . $love . '</span></span>';

I also used a bit of CSS for the styling of the button to give it a hover effect. It's not very obvious whether it's a button, but it will for our simple test.

.love-button img {margin-right: 6px; Opacity: 0.7; Cursor: pointer; } .love-button img: hover {opacity: 1; }

Love tutorial WordPress

Triggering an action

Finally, we come to our JavaScript! We must target our item and detect a click on it. Here's how to do it:

(function ($) {$ (document) .on ('click', '.love-button img', function () {alert ("love is shared");})}) (jQuery);

If you click the button at this point, you should see a JavaScript alert with the text "Love is shared." "

Data requirements

Instead of this text, we need to trigger an AJAX call. Before writing our code, we will understand what we need to send.

Are you looking for the best WordPress themes and plugins?

Download the best plugins and WordPress themes on Envato and easily create your website. Already more than 49.720.000 downloads. [EXCLUSIVE]


First of all, we need a place to send data. The place where we send the data, will process the data and answer the call. WordPress has a built-in place to handle AJAX calls, which we can use: the " admin-ajax.php " inside " wp-admin ". We cannot add this URL to our script (using "raw" coding is not acceptable), So we will use some WordPress trick.

The function wp_localize_script () Was originally intended to translate strings in JavaScript files, which it does well. We can also use it to pass variables to our JavaScript files, in this case the URL of our AJAX file. Add the following code to our file " functions " as following :

wp_localize_script ('ajax-test-scripts', 'ajaxTest', array ('ajax_url' => admin_url ('admin-ajax.php')));

The result of this last object will be named ajaxTest, which will contain a given array in the last parameter as properties. To enter the value we can use ajaxTest.ajax_url In our JavaScript code.

The identifier of the article

We will send arbitrary data as the identifier of the article (that we will use to identify the article on which we want to "add a little love"). This can be retrieved from the DOM. Take a look at the structure used in the "Twenty Sixteen" theme below:

article structure Twenty Sixteen

Our button has an "article" as one of its ancestors. This element has the class and contains the numeric identifier of the article. Although this is not the most elegant solution, we can grab the ID from there.

$ (Document) .on ('click', '.love-button img', function () {var post_id = parseInt ($ (this) .parents (''). .replace ('post-', '')) console.log (id)})

The action

WordPress also requires that we send a parameter named action. Since all actions will be sent to admin-ajax, we need a way to differentiate those requests, hence the use of this parameter.

Sending an AJAX request

We can now put everything together. We need to create an AJAX call for " wp-admin / admin-ajax.php Which contains the article ID and an action. This is how it should look.

(Function ($) {$ (document) .on ('click', '.love-button img', function () {var post_id = parseInt ($ (this) .parents (''). Attr ('id') .repos ('post-', '')); $ .ajax ({url: ajaxTest.ajax_url, type: 'post', data: {action: 'add_love', post_id: post_id} , Success: function (response) {alert ('success, the new count is' + response)}})})}) (jQuery);

$ .ajax () is the used function that takes a bunch of parameters. The url contains the target which is currently our file ajax-url.php ". The type is set to " post Like any request sent by a form. The data parameter is an object that contains " key-value That we want to send to the server. Later we will be able to read them with $ _POST ['action'] and $ _POST ['post_id'].

Processing the application

Normally you need to edit the file " admin-ajax.php », Because the request is sent there. It's a system file, so we're not going to modify it. WordPress allows you to pass AJAX requests using square brackets with the action parameter. The model is as follows:

If you named your action add_love You must attach a function to a hook named " wp_ajax_add_love " and or " wp_ajax_nopriv_add_love ". Actions " NoPriv ”Runs for logged out users, one triggers for logged in users only. In our case, we would like to use both. As a quick test, we'll set a default return value:

The success parameter is a function, which will run when the AJAX call is completed. We'll show a simple alert that shows “Well done! The new account is ”with our answer added at the end.

Add_action ('wp_ajax_add_love', 'ajax_test_add_love'); Add_action ('wp_ajax_nopriv_add_love', 'ajax_test_add_love'); Function ajax_test_add_love () {echo 4; die (); }

We attached our function to both brackets, one done threw out 4 and then used the function " die () ". This is necessary on WordPress, otherwise you will receive an 0 at the end of each answer. If you click on the button now you should see the following:

Example ajax button jquery

Easily create your Online Store

Download free WooCommerce, the best e-commerce plugins to sell your physical and digital products on WordPress. [Recommended]

To get the actual likes count all we need to do is retrieve the current number, increment it by one, save it to the database, and display the new number.

Function ajax_test_add_love () {$ love = get_post_meta ($ _POST ['post_id'], 'show_some_love', true); $ Love = (empty ($ love))? 0: $ love; $ Love ++; Update_post_meta ($ _POST ['post_id'], 'show_some_love', $ love); Echo $ love; die (); }

If you click on the button now you should see the pop-up window displaying "1". If you refresh the page, you should see the new number displayed. Clicking the button again will make it 2 ". All we need to do now is make sure the number is reflected directly in the UI.

Make changes on the user interface using the response

This part seems easy (because it is), but it is generally the most difficult to put together. For now all we need to do is locate the element that contains the current number and modify its content by the response.

(function ($) {$ (document) .on ('click', '.love-button img', function () {var post_id = parseInt ($ (this) .parents (''). find ('.' number) $ .ajax ({url: ajaxTest.ajax_url, type: 'post', data: {action: 'add_love', post_id: post_id,}, success: function (response) {$ number.text (response);}})}) (jQuery);

I only added two lines to our previous JS code. On line 5, I store the element that contains the number on the variable $ number. On the 14 line, I modify the text of this element to display the answer, which is the new number.

That's it, basically you should be able to see this new feature in action on your custom theme. If you have any problem, please let us know. Do you have another tip that you want to share? Do it in the comments section.

This article features 0 comments

Leave a comment

Your email address will not be published. Required fields are marked with *

This site uses Akismet to reduce unwanted. Learn more about how your comments data is used.

Back To Top