PHP mt_rand() Function
<?php echo(mt_rand() . "<br>"); echo(mt_rand() . "<br>"); echo(mt_rand(10,100)); ?>
Syntax mt_rand(); or mt_rand(min,max);
php version เก่า
<?php echo rand() . "\n"; echo rand() . "\n"; echo rand(5, 15); ?>
ตัวอย่างการนำไปใช้
โดยสร้าง 1.css และ 2.css ใน folder เพื่อสุ่ม css
<link href="/styles/<?php echo mt_rand(1,2); ?>.css" rel="stylesheet" type="text/css"/>
ยังมีวิธีอื่นๆ
สำหรับ wordpress
How to enqueue a random css style?
I want a random CSS style file to load on my site with each page view so I can play with colors backgrounds.
So I put all my styles in a folder, I named them 1.css, 2.css, etc. and I have added:
<link rel='stylesheet' id='name-random-color-css' href='http://www.url.com/wp-content/themes/themename/inc/rcolor/<?php echo mt_rand(1, 9) ?>.css' type='text/css' media='all' />
in the header.
It works but I know this is not the proper way to include styles in WordPress. I should utilize the wp_enqueue_style function in the functions.php file, but I don’t know how to combine the two to make it work.
ตอบ
ใส่ใน functions.php
function enqueue_random_style() { wp_enqueue_style( 'style-name', get_stylesheet_directory_uri() . '/inc/rcolor/' . mt_rand(1, 9)); } add_action( 'wp_enqueue_scripts', 'enqueue_random_style' );
https://wordpress.stackexchange.com/questions/164079/how-to-enqueue-a-random-css-style
การสุ่ม background
https://teamtreehouse.com/community/random-background-color