Random post category URL

时间:2015-02-14 作者:Ferrmolina

我正在尝试获取一个随机的帖子URL,只在当前类别中。这是我的代码,它返回URL类别:/

<?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>\';
?>
你能帮我吗?

1 个回复
最合适的回答,由SO网友:TheDeadMedic 整理而成

专业提示-除非需要,否则不要自定义查询。永远不要使用guid 领域

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

结束