Home >Backend Development >PHP Tutorial >How to Display Random Quotes with AJAX in a WordPress Shortcode?

How to Display Random Quotes with AJAX in a WordPress Shortcode?

Linda Hamilton
Linda HamiltonOriginal
2024-12-08 21:35:20393browse

How to Display Random Quotes with AJAX in a WordPress Shortcode?

How to Generate Random Quotes Using 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:

  1. The shortcode random_quote generates an initial random quote and a button labeled "New Quote."
  2. When the "New Quote" button is clicked, the jQuery handles the AJAX request.
  3. The handler function load_random_quote returns a new random quote, which is then displayed by the jQuery in place of the previous one.
  4. To prevent security issues, the AJAX nonces have been implemented.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn