doumao1519
2015-10-01 02:56
浏览 46
已采纳

WordPress - 显示190-250之间的随机数

Does anyone know of a way to display a random number between 190-250 inside a specific page?

For example: Today I had Display Random Number Coffees.

图片转代码服务由CSDN问答提供 功能建议

是否有人知道如何在特定页面内显示190-250之间的随机数?

例如: 今天我有显示随机数咖啡。

  • 写回答
  • 好问题 提建议
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • doumengxue7371 2015-10-01 03:39
    已采纳

    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"]

    已采纳该答案
    评论
    解决 无用
    打赏 举报
  • doukui7574 2015-10-01 06:46

    You can also use the PHP rand function in the page where you want it:

    echo(rand(190,250));
    
    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题