Skip to content

Instantly share code, notes, and snippets.

@moimikey
Created September 12, 2012 04:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moimikey/3704281 to your computer and use it in GitHub Desktop.
Save moimikey/3704281 to your computer and use it in GitHub Desktop.
super fast random WordPress tag
<?php
/**
* Return a random post tag from the wp_terms table
*
* average 0.4ms on a 3K table
*
* @author Michael Scott Hertzberg
* @return mixed|string
*/
function m_random_tag() {
global $wpdb;
return $wpdb->get_var( $wpdb->prepare( 'SELECT name FROM wp_terms JOIN( SELECT CEIL(RAND() * (SELECT MAX(term_id) FROM wp_terms)) AS term_id) AS m USING( term_id );' ) );
}
@franz-josef-kaiser
Copy link

Afaik there's a 'order' => 'rand' arg by default in get_terms().

@moimikey
Copy link
Author

benchmark comparison to order rand, my sql statement is a lot quicker

@hitpopking
Copy link

Can you do a fast random post for wordpress, I have been trying for the past 3 hours, but they all take longs on my database (4k records)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment