Easy using AJAX in WordPress without plugin

AJAX has become a popular plugin since coming to life. In today’s article, we will understand how to use ajax in WordPress without plugins. Any WordPress developer sooner or later feels the need of using it as soon as it is an undeprivable part of technology.

When use plugins and when don’t

Although you will find a ton of plugins that will offer you their support in custom solutions you need it is not always the right and efficient to use them. Personally, when doing the orders of clients and when asking myself which option shall I go for. I start to estimate which of three options the current solution falls into. Here are those three options.

1. When what you want the plugin does 100%

When the plugin does 100% of the job needed there is absolutely no reason to write the code again. However, this happens very rarely.

Precaution: If the plugin you use makes too many AJAX calls it may result in slow performance of the website, you need to start coding your custom solution.

2. When the plugin does the job partly and you need to add functionality

First, you need to determine what is done and what needs to be added. If the plugin does just 20% of the job that needs to be done it will take longer time and finances to add functionality to the plugin

And if on the contrary, the plugin does 80% percent of the job there is no need to code everything from scratch. It will cost you time for you and the project and will cost money to the client.

3. When there is no plugin doing the job

If you are in this situation don’t panic. It is not hard to make AJAX requests in WordPress pr PHP. WordPress of course makes the job easier, but it is hard to do in other PHP or other server-side languages environments as well. Continue reading and we will cover topics step by step.

How AJAX calls work in WordPress

First of all, let’s understand that there are many ways of using AJAX in WordPress without the plugin. But only one of them is supported by the WordPress community that is using the admin-ajax.php file located in the wp-admin folder of your theme directory.

Mostly we are going to use AJAX requests with jQuery, as soon as it is much simpler compared to vanilla JS, using which became a trend in recent years.

Before we move on to the basics of ajax in WordPress without plugins we need to understand the general principles of the functionality.

General information before using ajax in WordPress without a plugin

  1. We need to create two hooks when registering our function in functions.php file(wp_ajax_action and wp_ajax_nopriv_action). For the action part, you put the neam of the
  2. admin-ajax.php is part of WordPress AJAX API, so if for security reasons you will decide to lock file system, it won’t stop working.
  3. We need to be careful not to use AJAX extensively, as soon as it leads to pressure on hosting(or server).

Create category posts update using AJAX

For using AJAX requests from admin-ajax.php we first need to tell to Java Script what is the path to the file.

Unlike PHP where we have a native function called get_stylesheet_url() or get_theme_file_url(), we need first to create to localize it, you can read more about localization here. According to the official WordPress team, this is the only way to deal with this.

Here is how we are going to d this(see line 11-14):

//Ajax in wordpress without plugin - localization
function my_enqueue() {
  
    //Your enqueues
	wp_enqueue_script( 'jquery' );
	wp_enqueue_script( 'search-js', get_template_directory_uri() . '/search.js', array('jquery') );


    wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/my-ajax-script.js', array('jquery') );

    //Localization example
    wp_localize_script( 'ajax-script', 'my_ajax_object',
            array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );
//Ajax in wordpress without plugin - localization

After this step, we are sure that we can direct our JS code to the right location of admin-ajax.php. Let’s try to update post data by categories. First, let’s show our category names on any page(you can create a custom page using page-your-page-name.php).

//Ajax in wordpress without plugin - localization
<?php get_header() ?>

<?php $categories = get_categories(); ?>
<ul class="cat-list">
  <li><a class="cat-list_item active" href="#!" data-slug="">All projects</a></li>

  <?php foreach($categories as $category) : ?>
    
    <li>
      <a class="cat-list_item" href="#!" data-slug="<?php echo $category->slug ?>">
        <?php echo $category->name; ?>
      </a>
    </li>
  <?php endforeach; ?>
</ul>


<?php 
  $alaxCategries = new WP_Query([
    'post_type' => 'post',
    'posts_per_page' => -1,
    'order_by' => 'date',
    'order' => 'desc',
  ]);
?>

<?php if($alaxCategries->have_posts()): ?>
  <ul class="project-tiles">
    <?php
      while($alaxCategries->have_posts()) : $alaxCategries->the_post();
        the_title();
        echo "'/br'";
      endwhile;
    ?>
  </ul>
  <?php wp_reset_postdata(); ?>
<?php endif; ?>

<?php get_footer() ?>
 //Ajax in wordpress without plugin - localization

Next, we need to create a function in the function.php file which is going to give us the response with the updated data we need to show as soon as AJAX runs.

//Ajax in wordpress without plugin - PHP function
function filter_categories() {
	$categories = $_POST['category'];
  
	$ajaxCat = new WP_Query([
	  'post_type' => 'post',
	  'posts_per_page' => -1,
	  'category_name' => $categories,
	  'orderby' => 'menu_order', 
	  'order' => 'desc',
	]);
	$response = '';
  
	if($ajaxCat->have_posts()) {
	  while($ajaxCat->have_posts()) : $ajaxCat->the_post();
		$response .= "" . the_title() . "";
		echo '<xmp></xmp>';
	  endwhile;
	} else {
	  $response = 'empty';
	}
  
	echo $response;
	exit;
  }
  add_action('wp_ajax_filter_categories', 'filter_categories');
  add_action('wp_ajax_nopriv_filter_categories', 'filter_categories');
//Ajax in wordpress without plugin - PHP function

Code explanation:

  1. Line 3 – Categories variable holds the value of the posted category name by JS code which we will write in the next step. On line 8 you can notice that we use the variable for the name of the category. (this value is updated by AJAX itself every time the user clicks).
  2. Line 5 – this variable generates a query every time an AJAX call is executed in our Java Script code.
  3. Line 12 -response variable is going to hold the content generated by WP_Query and will later be assigned to our DOM element as its innerHTML(or just HTML if you use jQuery)

And our last step which we need to do is to use JS code to trigger AJAX queries.

//Ajax in wordpress without plugin - JS function
jQuery('.category_item').on('click', function() {
 
  jQuery.ajax({
    type: 'POST',
    url: my_ajax_object.ajax_url,
    dataType: 'html',
    data: {
      action: 'filter_projects',
      category: jQuery(this).data('slug'),
    },
    success: function(response) {
      jQuery('.category-tiles').html(response);
    }
  })
});
//Ajax in wordpress without plugin - JS function

Code explanation:

  1. JQuery.ajax() – you can read more about this function here.
  2. URL – hold the value of the path of the file to which the request is sent.
  3. data – action in data holds the name of the AJAX call we have created(for example if it is wp_ajax_filter_categories then we shall type here “filter_categories”, don’t confuse it with the name of the function in functions.php). The category is the string posted by JS to PHP(we get it on line 3 of PHP code. The name category and what we get in PHP shall match)

Conclusion

We have gone by all the basics of AJAX and did a practical example. You can follow this post to see and try more practical examples of AJAX.

Katen Doe

Hovhannes Verdyan

Hello, I’m a developer who loves WordPress and loves helping peopls let me know if you have any question by leaving your question in comments in one of my youtube videos. Click here to go to my channel.