Mục lục
Bạn có thể thử bằng cách bấm vào liên kết bên dưới.
PHP
Đầu tiên, tạo một hàm lấy bài viết ngẫu nhiên tại functions.php.
function get_random_post_url() {
$rand_args = array(
'post_type' => 'post',
'posts_per_page' => 1,
'orderby' => 'rand'
);
$result = '#';
$rand_query = new WP_Query($rand_args);
if ($rand_query->have_posts()) {
while ($rand_query->have_posts()) {
$rand_query->the_post();
$result = get_the_permalink();
}
}
wp_reset_query();
return $result;
}
HTML
Để sử dụng, bạn chỉ cần làm như sau.
<a href="<?php echo get_random_post_url(); ?>">Bài viết ngẫu nhiên</a>
Cách sử dụng khác
Nếu bạn muốn chuyển hướng về một bài viết ngẫu nhiên khi truy cập một liên kết cố định, ví dụ /?random, thì thêm đoạn mã sau vào funtions.php.
function custom_redirect_on_parameter() {
if (strpos($_SERVER['REQUEST_URI'], '?random') !== false) {
$random_post = get_posts(array(
'numberposts' => 1,
'orderby' => 'rand',
'post_type' => 'post',
));
if (!empty($random_post)) {
$random_post_id = $random_post[0]->ID;
$random_post_url = get_permalink($random_post_id);
wp_redirect($random_post_url);
exit;
}
}
}
add_action('template_redirect', 'custom_redirect_on_parameter');
Chúc các bạn thành công!
Bình luận