WordPress – Display Random Number Between 190-250

The way I would accomplish this is with a shortcode, like this:

function na_random_number_shortcode( $atts ) {
    global $post;

    $args = shortcode_atts(
        array(
            'min'  => 190,
            'max' => 250,
            'id' => $post->ID,
            'hours' => 24
        ),
        $atts, 'random_number'
    );

    // Use transient to store the random number temporarily 
    if ( false === ( $random_number = get_transient( 'random_number_'.$args['id'] ) ) ) {
        $random_number = mt_rand( (int) $args['min'], (int) $args['max'] );
        set_transient( 'random_number_'.$args['id'], $random_number, HOUR_IN_SECONDS * $args['hours'] );
    }

    return $random_number;
}
add_shortcode( 'random_number', 'na_random_number_shortcode' );

Putting that code in your theme’s functions.php file would allow you to enter

“Today I had [random_number] Coffees.”

and display a random number between 190 and 250.

It’s also flexible; you can do something like [random_number min="1" max="10"] to get a random number between 1 and 10.

By default, it will remember the random number for 24 hours. You can change this by passing in the “hours” attribute, like: [random_number hours="12"]

If you have more than one of these on a page, and you want the numbers to be different, you have to give each one a unique id. So if you had two of them, you could do: [random_number id="1"] and [random_number id="2"]

Leave a Comment