Generating a random number on every post and saving it in database

I want to generate two random numbers above every post and save them in the database so that it won’t change every time we see or refresh that page.

I’ve decided to put this php code inside my single.php file of my theme for the random number:

<?php echo rand(1000, 10000); ?>

and put this one for random decimal number:

<?php echo $rand = 0.1*rand(40,49)?>

but they generate random numbers between specified values every time the visitor sees the page. I want to know how to generate those random numbers and store them along with other contents of the page in the database.

1 Answer
1

I guess you mean something like this:

if( function_exists( 'get_post_random_wpse' ) )
    echo get_post_random_wpse( 
        $post_id    = get_the_ID(), 
        $meta_key   = '_post_random', 
        $meta_value = rand( 1000, 10000 ) 
    ); 

where:

function get_post_random_wpse( $post_id = 0, $meta_key = '_post_random', $meta_value = 0 )
{
    if( ! ( $post_id > 0 && strlen( $meta_key ) > 0 ) )
        return 0;

    if( '' === ( $post_rand = get_post_meta( $post_id, $meta_key, true ) ) ) 
            update_post_meta( $post_id, 
                $meta_key, 
                $post_rand = $meta_value 
            );

    return $post_rand;
}

where we use the post meta to store the random value for each post.

Update:

A comment response: It sounds like you want to store two random numbers for each post: _post_random_int and _post_random_dec where you display/store them with:

if( function_exists( 'get_post_random_wpse' ) )
    echo get_post_random_wpse( 
        $post_id    = get_the_ID(), 
        $meta_key   = '_post_random_int', 
        $meta_value = rand( 1000, 10000 ) 
    ); 

and

if( function_exists( 'get_post_random_wpse' ) )
    echo get_post_random_wpse( 
        $post_id    = get_the_ID(), 
        $meta_key   = '_post_random_dec', 
        $meta_value = 0.1 * rand( 42, 49 ) 
    ); 

but you should avoid cowboy coding on a live site and test this on a dev (localhost) install.

Notice that the underscore in the meta key, makes the custom fields unaccessible from the backend UI. If you want to be able to modify the custom fields from the backend, don’t use the underscore, use e.g. post_random instead of _post_random.

Leave a Comment