tags:

views:

4

answers:

1

I have 3 custom fields on a page, they are dailytip_1, dailytip_2 and dailytip_3.

So I want to show only 1 tip of the 3 tips randomly on the page. What I can do? Thanks!

<?php $dailytip_1 = get_post_meta($post->ID, 'dailytip_1', true); ?>

<?php if ($dailytip_1 !== '') { ?>
    <p><?php echo get_post_meta($post->ID, 'dailytip_1', true); ?></p>
<?php } ?>
A: 

Does the following help?

<?php
    $random_dailytip = 'dailytip_' . rand( 0, 2 );
    $dailytip = get_post_meta($post->ID, $random_dailytip, true);

?>

<?php if ($dailytip !== '') { ?>
    <p><?php echo get_post_meta($post->ID, $random_dailytip, true); ?></p>
<?php } ?>

As you can see, $random_dailytip gets the values dailytip_0, dailytip_1 or dailytip_2 randomly.

Alan Haggai Alavi
That works. Actually i have 5 tips and the array, then it should be rand(0,4). shouldn't it? Thanks Alan.
ray
Yes, it should be `rand( 0, 4 )` in that case. You are welcome.
Alan Haggai Alavi
I'm keep refreshing the page. It seems that it doesn't get any content sometime. And I'm sure I put all the values for all the 5 tips, anyidea?
ray
I see it begins from dailytip_0 Have changed it to rand( 1, 5 ). Should be good now. right?
ray
I have updated the code a bit. Can you please try again?
Alan Haggai Alavi
Well, if you want a range of 1 to 5, you can use `rand( 1, 5 )`.
Alan Haggai Alavi
It's working great now. Thank you!
ray
Nice to know that. Then, try considering accepting my answer.
Alan Haggai Alavi
Yes! just done that.
ray