0

Here is an example

Cat 1 has 6 post: ( post 1 , post 2 , post 3, post 4 etc.. )

Cat 2 has 6 post: ( post 1 , post 2 , post 3, post 4 etc.. )

i want to display random post like this:

Today's CAT 1 Random post : Post 2 Today's CAT 2 Random Post : Post 5

but the posts has to change per 24 hours. Is it possible. Thanks

( Sorry about my bad Eng )

1 Answer 1

1

You could always use get_posts() to return a random post, but it would change every time the page loaded. So, here's an idea for you.

In a plugin file, set up a wp_cron hook.

<?php
/* Your plugin header goes here */

register_activation_hook( __FILE__, 'wpse24234_activation' );
function wpseo24234_activation()
{
    wp_schedule_event( time(), 'daily', 'wpse24234_daily' );
}

Then hook a function into your cron action that grabs a random post (via get_posts()) and stores it in a transient that expires every 24 hours.

add_action( 'wpse24234_daily', 'wpse24234_daily_cb' );
function wpse24234_daily_cb()
{
    $posts = get_posts( array( 'cat' => YOUR_CATEGORY_ID_HERE, 'numberposts' => 1, 'orderby' => 'rand' ) );
    if( ! empty( $posts ) )
        set_transient( 'cat_1_post', $posts[0]->ID, 60 * 60 * 12 );
}

Then on the front end, you can get the post ID with get transient, and use the ID to pull in whatever other stuff you'd like.

<?php
/* Somewhere on your site */
$id = get_transient( 'cat_1_post' );

$link = '<a href="' . get_permalink( $id ) . '">' . get_the_title( $id ) . '</a>';
?>

Todays random post from Category 1 is <?php echo $link; ?>

You'll have to do some testing to see if this will work for you, of course.

8
  • thank you so much Christopher Davis ;) i m gonna try it r now Commented Jul 27, 2011 at 18:51
  • it didnt work :S Davis. Commented Jul 27, 2011 at 19:24
  • That's why I said you'd have to test it! Did you put it into a plugin file and active the plugin? Commented Jul 27, 2011 at 19:31
  • yes. i added all codes my themes functions.php and i added the last code to my sidebar.php. The result comes but that post link not from the choosen category it choosen from the all categories. Ps. I edited the YOUR_CATEGORY_ID_HERE line too. Commented Jul 27, 2011 at 19:36
  • That would explain why it didn't work. You have to call wp_schedule_event one time (on plugin activation), there's not a theme activation hook to do that. Take a look at this: codex.wordpress.org/Writing_a_Plugin#File_Headers that's what I meant by /* your plugin header goes here */ Commented Jul 27, 2011 at 19:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.