To display the current date and time using AJAX in WordPress, you can follow these steps:
- First, create a new WordPress plugin or open an existing one.
- Enqueue jQuery and your custom script file in the plugin’s main PHP file or in your theme’s
functions.phpfile. Here’s an example:
function wp_ajax_current_datetime_scripts() {
wp_enqueue_script( 'my-ajax-script', plugin_dir_url( __FILE__ ) . '/js/ajax-script.js', array( 'jquery' ), '1.0', true );
wp_localize_script( 'my-ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'wp_ajax_current_datetime_scripts' );
- Create a new JavaScript file, for example
ajax-script.js, in the plugin or theme directory and add the following code:
jQuery(document).ready(function($) {
$.ajax({
url: my_ajax_object.ajax_url,
type: 'POST',
data: {
action: 'get_current_datetime'
},
success: function(response) {
// Display the response in your desired format
console.log(response);
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}
});
});
- Create a PHP function to retrieve the current date and time and register it as an AJAX action. Add the following code to your plugin’s main PHP file or in your theme’s
functions.phpfile:
function get_current_datetime() {
echo date_i18n( get_option( 'date_format' ) . ' ' . get_option( 'time_format' ) );
wp_die();
}
add_action( 'wp_ajax_get_current_datetime', 'get_current_datetime' );
add_action( 'wp_ajax_nopriv_get_current_datetime', 'get_current_datetime' );
That’s it! When you access a page that loads the JavaScript file, it will make an AJAX request to retrieve the current date and time, and display it in the console. You can modify the JavaScript code to display the date and time on your webpage as per your requirement.
Make sure you have PHP error logging enabled while developing, as any syntax errors or issues in the code may result in a blank response or an error message.
Remember to replace the console.log(response); line with the appropriate code to display the response on your webpage.
