We have already shared a code to help you about passing PHP variables to JavaScript function. Now we are going to share a more practical example by using that code snippet i.e Using Ajax in WordPress

We will recommend to have a look on that code so it will be easy to learn the following tutorial for you. We have written a very basic and simple tutorial that will explain the usage of Ajax in WordPress with the help of admin-ajax.php

Let start our tutorial,

1. Basic WordPress Loop – index.php

<?php get_header();	?>

<div id="ajax-response"></div>          
<ul>
<?php 
if ( have_posts() ) :
while ( have_posts() ) : the_post();
?>	
  <li><a href="#" id="<?php the_ID(); ?>" class="ajax-post"><?php the_title(); ?></a></li>
<?php 
endwhile;
endif;
?>
</ul>

<?php get_footer(); ?>

You have noticed that we have simplified the template in order to focus on our example. Nothing special – just a standard WordPress loop and an Ajax Response Div to load the post contents via Ajax.

2. Ajax Logic – functions.php

You can place the following codes in the functions.php file. Let segregate these codes to make the tutorial easy,

A. Register / Enqueue Scripts

/** Register Scripts. */
add_action( 'wp_enqueue_scripts', 'theme_register_scripts', 1 );
function theme_register_scripts() {

  /** Register JavaScript Functions File */
  wp_register_script( 'functions-js', esc_url( trailingslashit( get_template_directory_uri() ) . 'functions.js' ), array( 'jquery' ), '1.0', true );

  /** Localize Scripts */
  $php_array = array( 'admin_ajax' => admin_url( 'admin-ajax.php' ) );
  wp_localize_script( 'functions-js', 'php_array', $php_array );

}

/** Enqueue Scripts. */
add_action( 'wp_enqueue_scripts', 'theme_enqueue_scripts' );
function theme_enqueue_scripts() {

  /** Enqueue JavaScript Functions File */
  wp_enqueue_script( 'functions-js' );

}

We have registered and load our functions.js file by implementing the recommended procedure of WordPress. Most notable thing is the wp_localize_script where we have passed admin-ajax.php path to our functions.js file.

Other logic is simple that we have loaded our JavaScript file to write Ajax logic. Now proceed to our second part of functions.php file,

B. Method Example that will be Called Via Ajax

/** Ajax Post */
add_action( ‘wp_ajax_theme_post_example’, ‘theme_post_example_init’ );
add_action( ‘wp_ajax_nopriv_theme_post_example’, ‘theme_post_example_init’ );
function theme_post_example_init() {

/** Made Query */
$args = array( ‘p’ => $_POST[‘id’] );
$theme_post_query = new WP_Query( $args );
while( $theme_post_query->have_posts() ) : $theme_post_query->the_post();
?>

” title=”” rel=”bookmark”>

Ajax Response wrapper.

3. Ajax Call – functions.js

We are near to end and here is the code about WordPress Ajax in the functions.js file,

(function($) {

	/** jQuery Document Ready */
	$(document).ready(function(){

		$( 'a.ajax-post' ).off( 'click' ).on( 'click', function( e ) { 

			/** Prevent Default Behaviour */
			e.preventDefault();

			/** Get Post ID */
			var post_id = $(this).attr( 'id' );

			/** Ajax Call */
			$.ajax({

				cache: false,
				timeout: 8000,
				url: php_array.admin_ajax,
				type: "POST",
				data: ({ action:'theme_post_example', id:post_id }),

				beforeSend: function() {					
					$( '#ajax-response' ).html( 'Loading' );
				},

				success: function( data, textStatus, jqXHR ){

					var $ajax_response = $( data );
					$( '#ajax-response' ).html( $ajax_response );														

				},

				error: function( jqXHR, textStatus, errorThrown ){
					console.log( 'The following error occured: ' + textStatus, errorThrown );	
				},

				complete: function( jqXHR, textStatus ){
				}

			});

		});

	});

})(jQuery);

JavaScript code for the WordPress Ajax logic is self-explanatory. Just try it and don’t forget to share your experience in the form of comments.

You may also be interested in our other articles on wordpress variables in javascript, wordpress adding fields to categories, exclude categories from blog wordpress and wordpress get taxonomies for post.

5 thoughts

  1. Hi, great tutorial i found it pretty useful.

    Unfortunately i encounter a problem. In the php function theme_post_example_init, the $_POST does not contain the id I send through my ajax call. It would be nice if someone has any ideas to resolve that.

    Thanks

  2. Hi there, in the B. Method Example that will be Called Via Ajax is there something missing?
    When i add the code to my functions.php it causes an error.
    It all appears to work however doesn’t actually display anything.
    Is that because Part B is the template?
    Thanks!

Leave a Reply to lindsayanng Cancel reply