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

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.

  • 写回答

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 请问这个是什么意思?
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏