Random element in get_post_meta array

account_circle Unassigned
schedule 3 Days
account_balance_wallet $5


I have a custom field that contains a list of comma separated colors.

I want to randomly select one of those colors.

If get_post_meta returns an array I thought I could randomly pick from that array.

If I try to echo $rand_color_value it just gives me the whole array

How can I randomly select one color from the list in the custom field.

        $agrs = array(

        'post_type' => 'page',

        'tag' => 'colors'


        $colorLoop = new WP_Query($agrs);




        $theColor = get_post_meta($post->ID, 'colors', false);

        /*random color*/

        $rand_color = array_rand($theColor,1);

        $rand_color_value = $theWeight[$rand_color];

        echo $rand_color_value; 


        <?php endwhile; endif;?>

        <?php wp_reset_postdata; ?>

Mar 19th, 2018
OK this is easy. First we parse the string to array. Then we random gerenate a number. Then we use index to choose the position in the array.

$array = explode(",", $yourDatabaseString);
$size = count($array);
$rand = rand(0, $size-1);
$result = $array[$rand];
Jun 12th, 2013

Did you know? You can earn $20 for every friend you invite to Studypool!
Click here to
Refer a Friend
Mar 19th, 2018
Mar 19th, 2018
Mar 20th, 2018
Mark as Final Answer
Unmark as Final Answer
Final Answer

Secure Information

Content will be erased after question is completed.

Final Answer