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