WordPress fetch image using ajax

fetch image using ajax

In this blog we will load images using ajax on page or post.

We will create shortcode for fetch image using ajax. it will speed up your page loading time.

I added code in child theme function.php file.

We will use ajax code using shortcode like below

[blog_image id='68'] 

To create shortcode use below code

function blog_img_func($atts){

/*The ob_start() function creates an output buffer.*/	 
ob_start(); ?>

/* Create hidden field to store image id*/	
<input type="hidden" class="blog_img_cls" value="<?php echo $atts['id'];?>" />
	 
/*Show ajax response in here*/
<div class="blog_img_div_<?php echo $atts['id']; ?>"></div>

/*The ob_get_clean() function returns the contents of the output buffer and then deletes the contents from the buffer.*/	
<?php return ob_get_clean();
}
/*The add_shortcode function is used to register a shortcode handler.*/
add_shortcode('blog_image','blog_img_func');

Below is wordpress hooks. they used to handle AJAX requests on the site when user log-in or not log-in. if you use both then it will work both login user or non login user

/*it will handle AJAX requests when user not login */
add_action("wp_ajax_blog_img_fetch", "blog_img_fetch");

/*it will handle AJAX requests when user login */
add_action("wp_ajax_nopriv_blog_img_fetch", "blog_img_fetch");

Ajax function in wordpress hooks to fetch image

function blog_img_fetch() { 

/*check nonce*/
 if ( !wp_verify_nonce( $_REQUEST['nonce'], "blog_img_fetch_nonce")) {
      exit("No naughty business please");
   } 
/*check nonce*/

/*get image id which add in shortcode*/
$post_id=$_REQUEST['post_id'];
 
/*use loop when multiple shortcode use on same page or post*/
foreach($post_id as $post_id_img){
	$response[$post_id_img]=wp_get_attachment_image($post_id_img,'full');
}
/*use loop when multiple shortcode use on same page or post*/

/*Sends a JSON response back to an Ajax request.*/
wp_send_json($response);

/*Kills WordPress execution after send a JSON response */
die();  
 
}

Register script to add jQuery code


/* init hook runs after WordPress has finished loading but before any headers are sent. */
add_action( 'init', 'my_script_enqueuer' );

function my_script_enqueuer() { 

/*add default wordpress jquery*/
wp_enqueue_script( 'jquery' );

/*register script to add jquery code*/
wp_enqueue_script('blog_img_fetch_script', get_stylesheet_directory_uri().'/blog_img_script.js', array('jquery'));

/*localizes a registered script with data for a JavaScript variable.*/
wp_localize_script('blog_img_fetch_script','blogFetchAjax', array('ajaxurl' => admin_url( 'admin-ajax.php' ),'security' => wp_create_nonce('blog_img_fetch_nonce')));   

/*register script*/
wp_enqueue_script( 'blog_img_fetch_script' );


}

Create file blog_img_script.js in child theme folder to add js code

Add below jQuery code in blog_img_script.js file

jQuery(document).ready( function() {

/*declare variable to store hidden field value of image id*/
var post_id=[];

  /*get hidden field value*/   
jQuery(".blog_img_cls").each(function(index,value){  
  post_id[index]=jQuery(this).val();
});
 /*get hidden field value*/ 

/*declare nonce variable*/
var nonce =  blogFetchAjax.security;
     
 /*ajax code*/
jQuery.ajax({
         type : "post",
         dataType : "json",
         url : blogFetchAjax.ajaxurl,
         data : {action: "blog_img_fetch", post_id : post_id, nonce: nonce},
         success: function(response) {
			 
			jQuery.each(response, function(key,val) {
             jQuery('.blog_img_div_'+key).html(val);
        });
			 
         }
      }); 
/*ajax code*/
  

})

How to use shortcode

Go to “Media” menu in wordpress dashboard

Copy image id from url

Replace with id in shortcode

[blog_image id='600'] 

Now you can use shortcode on page or post or somewhere else in wordpress to fetch image using ajax

Full Code

Finally, it is time to insert the code to your functions.php file.

1. Log in to your WordPress admin area. Then, navigate to Appearance -> Theme Editor -> Theme Functions.
2. Paste the code from your text editor to the bottom of functions.php file. Click Update File to save the changes.

add_action("wp_ajax_blog_img_fetch", "blog_img_fetch");
add_action("wp_ajax_nopriv_blog_img_fetch", "blog_img_fetch");

function blog_img_fetch() { 

 if ( !wp_verify_nonce( $_REQUEST['nonce'], "blog_img_fetch_nonce")) {
      exit("No naughty business please");
   } 
   
$post_id=$_REQUEST['post_id'];
foreach($post_id as $post_id_img){
	$response[$post_id_img]=wp_get_attachment_image($post_id_img,'full');
}
wp_send_json($response);
die();  
 
}

add_action( 'init', 'my_script_enqueuer' );

function my_script_enqueuer() { 
wp_enqueue_script( 'jquery' );
wp_enqueue_script('blog_img_fetch_script', get_stylesheet_directory_uri().'/blog_img_script.js', array('jquery'));
wp_localize_script('blog_img_fetch_script','blogFetchAjax', array('ajaxurl' => admin_url( 'admin-ajax.php' ),'security' => wp_create_nonce('blog_img_fetch_nonce')));   
wp_enqueue_script( 'blog_img_fetch_script' );

}


function blog_img_func($atts){
	 ob_start(); ?>
	 <input type="hidden" class="blog_img_cls" value="<?php echo $atts['id'];?>" />
	 <div class="blog_img_div_<?php echo $atts['id']; ?>"></div>
	<?php
	  return ob_get_clean();
}

add_shortcode('blog_img','blog_img_func');


 

Leave a Comment

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

Scroll to Top