I needed a placeholder for tags input but it’s boring to display the same tags every time. But unlike posts, WP doesnt have “rand” orderby paramater. So what you can do; is to get a #no of tags and shuffle them.

tagdUntitled-6

So basically what we do is:

  1. Check if we have a recent transient
  2. If not, query the tags.
  3. Note the allowed orderby parameters for tags are defined as $tag_rnd_arr, which will add more randomness to them
  4. 11 is the number of tags to get, 3 is the number of tags to return. You can increase or decrease them
function eobtn_get_rand_tags() {
	$rand_tags = get_transient("rand_tags");
	// Check if we have queried 3 random tags recently
	if(!$rand_tags) {
		$tag_rnd_arr = array("name","count","term_id");
		$tag_argz=array(
		"orderby" => array_rand($tag_rnd_arr),
		"order" => "DESC",
		"number" => 11,
		"hierarchical" => false,
		"fields" => "names"
		);
		$tags = get_tags($tag_argz);
		$rand_tags = array();
		shuffle($tags);
		$ran_key_arr = array_rand($tags, 3);
		foreach ($ran_key_arr as $ran_tag ) {
			$rand_tags[] = $tags[$ran_tag];
		}
		// Save the result for a short time (3 secs) to save an extra query hit if you have thousands of tags and / or visitors
		set_transient("rand_tags",$rand_tags, 3);
	}
	return $rand_tags;
}

If you need echoing them instead of returning, you can simply echo them using

	if ($rand_tags) {
	  foreach($rand_tags as $tag) {
		  echo '<a href="'.get_tag_link($tag->term_id).'">'.$tag->name . '</a>';
		  if($tc != 3 || $ttc != 1)  echo ', ';
	  }
	}

It should look like thistaggClipboard01

Leave a Reply

Your email address will not be published.