WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I have the following code to the shortcode to display a random quote. Question: how to make a button display a new random quote? I mean, that would hit the button and show you a new quote (without refreshing the page of course).

function random_quote() {

    // quotes file
     $array = file("/path to txt file");

    // generate a random number between 0 and the total count of $array minus 1
    // we minus 1 from the total quotes because array indices start at 0 rather than 1 by default
    $r = rand(0,count($array)-1);

    // return the quote in the array with an indices of $r - our random number
    return $array[rand(0,count($array)-1)];

add_shortcode( 'randomquotes', 'random_quote');

I'm interested in how you can update the content on the page using ajax in WordPress? In my situation, because in fact be exactly that.

Sorry for my bad English. I hope you understand me. Thanks!

share|improve this question
up vote 3 down vote accepted

First off, this is very borderline within the scope of WPSE, it at all.
Apart from the shortcode to trigger the initial HTML output, this is really just AJAX.

Anyhow, that being said, this is how it's done:


Assuming that the above PHP snippet you supplied is functional, place the following in a php file for the ajax call:


 /* uncomment the below, if you want to use native WP functions in this file */
// require_once('../../../../wp-load.php');

 $array = file( $_POST['file_path'] ); // file path in $_POST, as from the js
 $r = rand( 0, count($array) - 1 );

 return '<p>' . $array[$r] . '</p>';

For future reference and so as to make this answer useful to others: Note that wp-load.php must be included in order to make use of native WordPress functionality. The most commom case likely being either the need for WP_Query or $wpdb.

The HTML Structure

In a page content, a widget or a template file:

<div id="randomquotes">
    <p>I would rather have my ignorance than another man’s knowledge,
       because I have so much more of it.<br />
       -- Mark Twain, American author & Playwright</p>
<a id="newquote" class="button" href="#" title="Gimme a new one!">New Quote</a>

This you can obviously adjust to your liking, but for the sake of this example, this is what we're going with.
We will generate the above via a shortcode later.

The jQuery


function ajaxQuote() {
    var theQuote = jQuery.ajax({
        type: 'POST',
        url: ajaxParams.themeURI+'js/ajax-load-quote.php',
        /* supplying the file path to the ajax loaded php as a $_POST variable */
        data: { file_path: ajaxParams.filePath },
        beforeSend: function() {
        success: function(data) {
        complete: function() {
    return theQuote;
/* Loading screen to be displayed during the process, optional */
function ajaxLoadingScreen(switchOn,element) {
    /* show loading screen */
    if (switchOn) {
            'position': 'relative'
        var appendHTML = '<div class="ajax-loading-screen appended">
            <img src="'+ajaxParams.themeURI+'images/ajax-loader.gif"
                alt="Loading ..." width="16" height="16" /></div>';
        if( jQuery(''+element).children('.ajax-loading-screen').length === 0 ) {
            'display': 'block',
            'visibility': 'visible',
            'filter': 'alpha(opacity=100)',
            '-ms-filter': '"progid:DXImageTransform.Microsoft.Alpha(Opacity=100)"',
            'opacity': '1'
    } else {
        /* hide the loading screen */
            'display': '',
            'visibility': '',
            'filter': '',
            '-ms-filter': '',
            'opacity': ''
            'position': ''
/* triggering the above via the click event */
jQuery('#newquotes').click( function() {
    var theQuote = ajaxQuote();
    return false;

Putting it together in functions.php

Below your above snippet (which you will find included modified below), paste the following:

function random_quote( $atts ) {
    /* extracts the value of shortcode argument path */
    extract( shortcode_atts( array(
        'path' => get_template_directory_uri() . '/quotes.txt' // default, if not set
    ), $atts ) );
    $array = file( $path );
    $r = rand( 0, count($array) - 1 );
    $output = '<div id="randomquotes">' .
            '<p>' . $array[$r] . '</p>' .
        '</div>' .
        '<a id="newquote" class="button" href="#" title="Gimme a new one!">New Quote</a>';
    /* enqueue the below registered script, if needed */
    wp_enqueue_script( 'ajax-quote' );
    /* supplying the file path to the script */
            'filePath' => $path,
            'themeURI' => get_template_directory_uri() . '/'
    return $output;
add_shortcode( 'randomquotes', 'random_quote');
/* register the js */
function wpse72974_load_scripts() {
    if ( ! is_admin() ) {
            get_template_directory_uri() . '/js/ajax-load-quote.js',
            array( 'jquery' ),
add_action ( 'init', 'wpse72974_load_scripts' );

Optional: The css for the loading screen

.ajax-loading-screen {
    display: none;
    visibility: hidden;
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    width: 100%;
    background: #ffffff; /* the background of your site or the container of the quote */
    filter: alpha(opacity=0);
    opacity: 0;
    -webkit-transition:  opacity .1s;
    -moz-transition:  opacity .1s;
    -ms-transition:  opacity .1s;
    -o-transition: opacity .1s;
    transition: opacity .1s;
    z-index: 9999;
.ajax-loading-screen img {
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -8px 0 0 -8px;

Resources / Reading

share|improve this answer
Any reason not to use the built-in AJAX API? – toscho Nov 17 '12 at 22:43
@toscho Honestly - not too familiar with it. Worth a read? – Johannes Pille Nov 18 '12 at 1:33
Yes, absolutely. :) I’ll add an alternative. – toscho Nov 18 '12 at 2:48
Perfect! Thank you!<br/> A script will work, if you set the function argument? For example, to be in the shortcode to provide a link to a text file? <br/> function random_quote ($path) {      $ array = file ("$ path");<br/> ... [randomquote file = "http://exampe.com/file.txt"]<br/> So will it work? I'm not too versed in programming. – user23769 Nov 18 '12 at 11:01
I have updated the answer. It now includes a filepath being set by the shortcode [randomquotes path="path/to/file.txt"], passed down to the js and from there to the php script. – Johannes Pille Nov 18 '12 at 14:18

You can register a script in a shortcode. It will be printed into the footer, given the theme contains wp_footer().

How it works:

  1. Register the shortcode callback with add_shortcode().
  2. In the shortcode callback, register the script, then return the output.
  3. In the script add an update button, send a POST request to admin_url( 'admin-ajax.php' ) and fetch new data. Insert the returned data into the element with the shortcode.

Here is a sample script doing that. Two files: a PHP class and a JavaScript file. Both should sit in the same directory, for example ajax-shortcode-demo.


 * Plugin Name: AJAX Shortcode Demo
 * Description: How to use AJAX from a shortcode handler named <code>[ajaxdemo]</code>.

add_action( 'wp_loaded', array ( 'Ajax_Shortcode_Demo', 'get_instance' ) );

class Ajax_Shortcode_Demo
     * Current plugin instance
     * @type NULL|object
    protected static $instance = NULL;

     * Unique action name to trigger our callback
     * @type string
    protected $ajax_action = 'load_demo_data';

     * CSS class for the shortcode, reused as JavaScript handle.
     * Must be unique too.
     * @type string
    protected $shortcode_class = 'ajaxdemo';

     * Remeber if we had regsitered a script on a page already.
     * @type boolean
    protected $script_registered = FALSE;

     * Create a new instance.
     * @wp-hook wp_loaded
     * @return  object $this
    public static function get_instance()
        NULL === self::$instance and self::$instance = new self;
        return self::$instance;

     * Constructor. Register shortcode and AJAX callback handlers.
    public function __construct()
        add_shortcode( 'ajaxdemo', array ( $this, 'shortcode_handler' ) );

        // register the AJAX callback
        $callback = array ( $this, 'ajax_callback' );
        // user who are logged in
        add_action( "wp_ajax_$this->ajax_action", $callback );
        // anonymous users
        add_action( "wp_ajax_nopriv_$this->ajax_action", $callback );

     * Render the shortcode.
    public function shortcode_handler()

        return sprintf(
            '<div class="%1$s"><b>%2$s</b></div>',

     * Return AJAX result.
     * Must 'echo' and 'die'.
     * @wp-hook wp_ajax_$this->ajax_action
     * @wp-hook wp_ajax_nopriv_$this->ajax_action
     * @return int
    public function ajax_callback()
        echo $this->get_rand();

     * Random number.
     * @return int
    protected function get_rand()
        return rand( 1, 1000 );

     * Register script and global data object.
     * The data will be printent before the linked script.
    protected function register_scripts()
        if ( $this->script_registered )

        $this->script_registered = TRUE;

            // unique handle
            // script URL
            plugin_dir_url( __FILE__ ) . '/jquery-ajax-demo.js',
            // dependencies
            array ( 'jquery'),
            // version
            // print in footer

        wp_enqueue_script( $this->shortcode_class );

        $data = array (
            // URL address for AJAX request
            'ajaxUrl'   => admin_url( 'admin-ajax.php' ),
            // action to trigger our callback
            'action'    => $this->ajax_action,
            // selector for jQuery
            'democlass' => $this->shortcode_class

        wp_localize_script( $this->shortcode_class, 'AjaxDemo', $data );


jQuery( function( $ ) {

    var buttonClass = AjaxDemo.democlass + 'Button',
        // insert AJAX result into the shortcode element
        updateDemo = function( response ){          
            $( '.' + AjaxDemo.democlass ).find( 'b' ).html( response );
        // fetch AJAX data
        loadDemo = function() {
            $.post( AjaxDemo.ajaxUrl, { action: AjaxDemo.action }, updateDemo );

    // add an update button
    $( '.' + AjaxDemo.democlass )
        .append( ' <button class="' + buttonClass + '">New</button>' );

    // assign the clock handler to the button
    $( '.' + buttonClass ).click( loadDemo );

Result in a blog post:

enter image description here

share|improve this answer
+1 & Thanks for the above. Looks definitely worth reading up on. I think I get most of what's going on above, the codex pages are on my reading agenda and I probably will check out the source anyway. Still, allow me to fire 2 quick follow-up questions: I can see that using the API will be of advantage to me, the programmer (clean, concise, tied to the environment (i.e. WP)). 1. How about performance? Any gains or disadvantages compared to using jQuery directly (am aware of the performance gap to straight js)? 2. Is it as flexible? I.e. can I make use of the same callbacks and arguments? – Johannes Pille Nov 18 '12 at 15:25
@JohannesPille Performance is not perfect. On the other hand, you act now in a predictable environment, other plugins can re-use your code (hooks, functions), and you don’t have to know where WP is installed (the plugin directory/URL could be on a different server). Besides that it is the same like a custom solution. – toscho Nov 18 '12 at 21:31
@toscho When I enabled the define('WP_DEBUG', true); in my wp-config.php this solution generated an error: Strict Standards: call_user_func_array() expects parameter 1 to be a valid callback, non-static method Ajax_Shortcode_Demo::get_instance() should not be called statically in /var/www/.../public_html/wp-includes/plugin.php on line 496. Is this critical? I changed it a little: wordpress.stackexchange.com/q/196332/25187 – Iurie Aug 1 '15 at 18:41
@Iurie Yeah, that method has to be declared as static. I made an edit to my post for that. Thanks for the notice. I wouldn't write the code like this anymore. :) – toscho Aug 1 '15 at 20:50

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.