1

I'm trying to get a random post URL, only in current category. This is my code, this returns the URL category, :/

<?php
 $current_cat = get_the_category(); 
 $randomPost = $wpdb->get_var("
   SELECT guid 
   FROM $wpdb->posts 
   WHERE post_type = 'post' 
   IN wp_terms = $current_cat 
   ORDER BY rand() LIMIT 1");
 echo '<a href="'.$randomPost.'">
   <div id="temporadas-dropdown">EPISODIO AL AZAR</div>
   </a>';
?>

Can help me?

2

Pro tip - don't custom query unless you need to (you don't). And never use the guid field.

if ( is_singular() && $cats = get_the_category() )
    $cat_id = $cats[0]->term_id; // Category ID for current post
elseif ( is_category() )
    $cat_id = get_queried_object_id(); // Category ID for current archive
else
    $cat_id = 0; // No cats

$posts = get_posts(
    array(
        'posts_per_page' => 1,
        'orderby' => 'rand', // Here's our random magic
        'cat' => $cat_id,   
    )
);

if ( $posts ) {
    $random_url = get_permalink( $posts[0]->ID );
}
  • This work but... its return same url. perhaps the cache is bothering ? Thanks for pro tip – Ferrrmolina Feb 14 '15 at 21:05
  • 1
    Whoops - change order to orderby – TheDeadMedic Feb 14 '15 at 21:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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