http://codex.ww.wp.xz.cn/Class_Reference/WP_Query#Order_.26_Orderby_Parameters
http://codex.ww.wp.xz.cn/Class_Reference/WP_Query#Custom_Field_Parameters
http://codex.ww.wp.xz.cn/Template_Tags/get_posts
http://codex.ww.wp.xz.cn/Function_Reference/get_post_custom_values
try:
<?php $last_five = get_posts(array('posts_per_page' => 5, 'category__in' => array(129,131,318), 'orderby' => 'rand', 'meta_key' => 'Quote'));
if($last_five) {
$random = rand(0,count($last_five)-1);
$random_id = $last_five[ $random ]->ID;
$mykey_values = get_post_custom_values('Quote', $random_id);
if( $mykey_values ) foreach ( $mykey_values as $key => $value ) { echo "$value"; }
} ?>
(untested)
That’s worked really well thanks. It’s almost there.
One last thing – how can we encase the content of that custom field (‘Quote’) in the URL of the post that it is part of?
encase the content of that custom field (‘Quote’) in the URL of the post that it is part of?
change from:
{ echo "$value"; }
to:
{ echo '<a href="' . get_permalink($random_id) . '>' . $value . '</a>'; }
Perfect! Thank you very much.
Vielen Dank für Ihre Hilfe.
Hi Guys,
I have been trying to make my posts random, i’m still a newbiee coder, where do I implement that code, does it make all my feature content random?
Regards
@dimoas – next time, please start a new topic for your question. More people will see it and it is the preferred practice on WP support forums.
The above code only displays a custom field from random posts, not the entire post, a somewhat different approach is needed in your case.
There’s a number of ways to make posts random, they mostly all involve making a mySQL query that includes orderby RAND() in the query string. Alternately, one could use the PHP shuffle() function to randomize the array returned by the query. The following example modifies the main query, assigning the ‘rand’ value to the ‘orderby’ query variable. The query object transforms this into the orderby RAND() string in the actual query. This is only done for your home page. If you were to alter or remove the if(){} structure, the random feature could be applied to different pages, or to all pages if removed.
function dim_random( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
$query->set( 'orderby', 'rand' );
}
}
add_action( 'pre_get_posts', 'dim_random' );
Of the various ways to do this, this is one of the more efficient ways. You can add other restrictions by setting other query vars in addition to ‘orderby’. You can set anything outlined in the WP_Query class reference.
This code can be added to your theme functions.php file or made into a simple plugin. If you are changing theme files, you should do so using a child theme so your changes can persist through theme updates. More information on all of this can be found by searching the Codex.