Home >Backend Development >PHP Tutorial >How to Display Random Quotes with AJAX in a WordPress Shortcode?
Question:
How can we update page content using AJAX in WordPress?
Answer:
Here's an enhanced version of the code provided in the question, which implements AJAX functionality in a WordPress shortcode to display random quotes:
Shortcode (shortcode.php)
function random_quote_shortcode( $atts ) { $atts = shortcode_atts( array( 'path' => get_template_directory_uri() . '/quotes.txt' ), $atts ); $quotes = file( $atts['path'] ); $random_quote = $quotes[array_rand($quotes)]; $output = sprintf( '<div>
AJAX Handler (ajax-handler.php)
add_action( 'wp_ajax_load_random_quote', 'load_random_quote' ); add_action( 'wp_ajax_nopriv_load_random_quote', 'load_random_quote' ); function load_random_quote() { $quotes = file( $_POST['file_path'] ); $random_quote = $quotes[array_rand($quotes)]; echo $random_quote; wp_die(); }
jQuery Script (ajax-script.js)
jQuery(document).ready(function($) { $('#newquote').click(function(e) { e.preventDefault(); $.ajax({ url: ajaxurl, data: { action: 'load_random_quote', file_path: '<?php echo get_template_directory_uri() . '/quotes.txt'; ?>' }, success: function(data) { $('#randomquote').html(data); } }); }); });
Enqueue Scripts and Localize Data (functions.php)
function enqueue_ajax_scripts() { wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '/js/ajax-script.js', array('jquery'), '1.0.0', true ); wp_localize_script( 'ajax-script', 'ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) ); } add_action( 'wp_enqueue_scripts', 'enqueue_ajax_scripts' );
Explanation:
Additional Note:
If you're using a custom theme, replace get_template_directory_uri() with the appropriate function for your theme.
The above is the detailed content of How to Display Random Quotes with AJAX in a WordPress Shortcode?. For more information, please follow other related articles on the PHP Chinese website!