Programming
Random element in get_post_meta array

Question Description


Hi

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);

        if($colorLoop->have_posts()):

        while($colorLoop->have_posts()):

        $colorLoop->the_post();

        $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; ?>


Final Answer

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];

henry (1070)
Rice University

Anonymous
The tutor managed to follow the requirements for my assignment and helped me understand the concepts on it.

Anonymous
The tutor was knowledgeable, will be using the service again.

Anonymous
Awesome quality of the tutor. They were helpful and accommodating given my needs.

Studypool
4.7
Trustpilot
4.5
Sitejabber
4.4

Brown University





1271 Tutors

California Institute of Technology




2131 Tutors

Carnegie Mellon University




982 Tutors

Columbia University





1256 Tutors

Dartmouth University





2113 Tutors

Emory University





2279 Tutors

Harvard University





599 Tutors

Massachusetts Institute of Technology



2319 Tutors

New York University





1645 Tutors

Notre Dam University





1911 Tutors

Oklahoma University





2122 Tutors

Pennsylvania State University





932 Tutors

Princeton University





1211 Tutors

Stanford University





983 Tutors

University of California





1282 Tutors

Oxford University





123 Tutors

Yale University





2325 Tutors