In this post we will explain how to use Ajax in WordPress manually, if you want to avoid usage of plugins. Step-by-step we will explain how to implement Ajax call, how to send data, handle that request in backend, return JSON result and finally parse that JSON into regular HTML. In this example we will send post ID to backend and return title and permalink of that post. In a same way we can return anything (content, featured image, even list of posts etc.).
First of all, let's say that we have default page.php template with basic structure like this:
<?php get_header();
if(have_posts()):
while (have_posts()): the_post(); ?>
<?php echo get_the_ID(); ?>
<?php endwhile;
endif;
get_footer(); ?>
Now inside that PHP while loop we have just get_the_ID() PHP function that returns ID of current post. We will use that later. Now let's extend this code with Ajax call:
<?php get_header();
if(have_posts()):
while (have_posts()): the_post(); ?>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: "<?php echo admin_url( 'admin-ajax.php' )?>",
type:'POST',
data: {
"action" : "get_page_content",
"ourpageid" : <?php echo get_the_ID(); ?>
},
dataType: "json",
success:function(allresults){
// do things here
}
});
});
</script>
<div id="results"></div>
<?php endwhile;
endif;
get_footer(); ?>
Let's analyze this code. We have added some jQuery code inside <script> tags and div with ID "results". Please make sure that you have included jQuery library inside your header.php file or whenever you want, but that library must be included. Also notice that this Ajax call will start on document ready but you can modify it to start on some other event (click, hover etc.).
That would be enough for now in frontend, let's see what need to be done in backend and how to handle those Ajax requests. We have pointed that url in Ajax call will call admin-ajax.php file and action would be "get_page_content". Now we must find way to conect those things somehow. Next code must be added to functions.php file:
<?php function implement_ajax_whatever() {
if( (isset($_POST['ourpageid'])) ) {
global $wpdb;
$pageid = $_POST['ourpageid'];
$getpagesbyid = $wpdb->get_results(
"SELECT * FROM wp_posts WHERE ID = '$pageid'"
);
foreach ($getpagesbyid as $mypage) {
$onePage = array();
$onePage['mytitle'] = $mypage->post_title;
$onePage['mypermalink'] = get_permalink($mypage->ID);
$allPages[] = $onePage;
}
$getPages = json_encode($allPages);
}
echo $getPages;
exit;
}
add_action('wp_ajax_get_page_content', 'implement_ajax_whatever');
add_action('wp_ajax_nopriv_get_page_content', 'implement_ajax_whatever'); ?>
Let's analyze this backend code.
Now we can back to frontend part of the code and finish it with code for parsing JSON results in success function, so the full frontend code looks like:
<?php get_header();
if(have_posts()):
while (have_posts()): the_post(); ?>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
url: "<?php echo admin_url( 'admin-ajax.php' )?>",
type:'POST',
data: {
"action" : "get_page_content",
"ourpageid" : <?php echo get_the_ID(); ?>
},
dataType: "json",
success:function(allresults){
for (var i=0; i<=allresults.length; i++) {
$('#results').append("<span>"+allresults[i].mytitle
+"</span><br><span>"+allresults[i].mypermalink+"</span>");
}
}
});
});
</script>
<div id="results"></div>
<?php endwhile;
endif;
get_footer(); ?>