leo charre


wordpress mediatags random object

Description and synopsis

This is to select a random attachment object that is labeled with the wordpress media-tags plugin.

   mediatag_rand_object()

Argument is string or array.
The string or array are media tag slugs.
Returns one attachment object selected at random, containing one or more of the tag arguments.
If nothing found, returns undef(false).

For example, you want to choose a random attachment object that has the mediatag ‘home’

   $object = mediatag_rand_object('home');

   echo 'got: ' . $object->ID;

If you want to choose one random object from all of ‘home’, ‘party’ and ‘boo’ mediatags..

   $object = mediatag_rand_object(array('home','party','boo'));

Code

function mediatag_rand_object($tag) {
   $tags = array();

   if(is_array($tag)){$tags = $tag;}
   else { $tags[] = $tag; }

   $tagstring = implode( $tags, ',');

   $ar = get_attachments_by_media_tags("media_tags=$tagstring");  # if this is slow.. add &numberposts=100 to limit
   $arsize = count($ar);
   if ( !$arsize ){ return ; }

   $index = mt_rand(0, ($arsize-1));

   return $ar[$index];
}

How to use

Copy and past code into your themes/themeuser/functions.php

CAVEAT

If you put this into your functions.php, make sure there’s no trailing whitespace after the last php end tag.
This is a php bug, sort of- see, functions.php is run before headers are sent, so any whitespace you leave would be interpreted as html to send to the client browser, regardless if it’s whitespace or valid html.


Linux User