wordpress制作随机文章链接。

||功能:跳转到随机文章页面。
||代码:
<?php
$randomPost = $wpdb->get_var("SELECT guid FROM $wpdb->posts WHERE post_type = 'post' AND
post_status = 'publish' ORDER BY rand() LIMIT 1");
echo '<a href="'.$randomPost.'">随机文章</a>';
?>
||解释:
1.数据库查询语句:
  • SELECT guid – Select just the guid column value, which is where the URL to the post is located.
  • FROM wp_posts – From the posts table
  • WHERE post_type = 'post' – Since attachments are also saved in the posts table, we need to specify that we just want posts
  • AND post_status = 'publish' – We just want the published posts, not scheduled posts, not drafts
  • ORDER BY rand() – Get them in random order
  • LIMIT 1 – And get just one resul
2.输出随机文章页面的地址;
3.如果需要,可以为随机文章加上自定义的css格式。
–> Make it simple by using the WPDB class, which comes bundled into WordPress.

评论

(required. But it will not be published)