Here we will learn about Call Custom WordPress function using Ajax.
1. Create a child theme first and Custom code copied and paste into your child theme’s functions.php file.
2. If you are using AJAX on the front-end, you need to Create js file and your AJAX calls are in custom.js file, then add wp_localize_script for get admin-ajax.php put URL in this JS file like so:
<?php function myblog_enqueue_styles() { wp_enqueue_script( 'ajax-script', get_stylesheet_directory_uri().'/js/custom.js' , array( 'jquery' ) ); wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) ); } add_action('wp_enqueue_scripts', 'myblog_enqueue_styles'); ?>
3. In custom.js file, you can use ajax_object object in your JS file:
<script> jQuery( document ).ready( function() { jQuery( '.yout-class-name' ).click( function() { console.log('The function is hooked up'); jQuery.ajax({ type : 'post', dataType : 'json', url : ajax_object.ajax_url, data : { action: 'add_user_fn', // add your parameters here }, success: function( response ) { // Returns success json data console.log( response ); } }); }); }); </script>
4. Ajax handler function.
syntax:
<?php add_action( 'wp_ajax_add_user_fn', 'add_user_fn' ); add_action( 'wp_ajax_nopriv_add_user_fn', 'add_user_fn' ); ?>
wp_ajax_ – This Action is used for a user is logged in to the website.
wp_ajax_nopriv_ – This Action is used when the user is not logged in of the website.
Example:
<?php // register the ajax action for authenticated users add_action( 'wp_ajax_add_user_fn', 'add_user_fn' ); // register the ajax action for unauthenticated users add_action( 'wp_ajax_nopriv_add_user_fn', 'add_user_fn' ); // handle the ajax request function add_user_fn() { //add your logic here... $result = array( 'key' => 'value' 'key1' => 'value1' ); // in the end, returns success json data wp_send_json_success( $result ); // or, on error, return error json data wp_send_json_error( $result ); } ?>