WordPress Query based on random taxonomy

<?php

$all_books = get_terms( 'history_books' );           // Get all history book terms.
$rand_book = $all_books[ array_rand( $all_books ) ]; // Select one at random.
$related = get_posts(
    array(
        'posts_per_page' => 5,
        'tax_query'      => array(
            array(
                'taxonomy' => 'history_books',
                'terms'    => array( $rand_book->term_id ),
            )       
        )
    )
);

?>

<h3>
    <a href="https://wordpress.stackexchange.com/questions/104280/<?php echo get_term_link( $rand_book ) ?>">
        <img src="/path/to/images/terms_hsb<?php echo $rand_book->term_id ?>.jpg" alt="<?php echo esc_attr( $rand_book->name ) ?>" />
        <?php echo esc_html( $rand_book->name ) ?>
    </a> (<?php echo $rand_book->count ?>)
</h3>

<?php if ( $related ) : ?>

    <ul class="related">
        <?php foreach ( $related as $post ) : setup_postdata( $post ) ?>

            <li><a href="https://wordpress.stackexchange.com/questions/104280/<?php the_permalink(); ?>"><?php the_title(); ?></a></li>

        <?php endforeach ?>
    </ul>

<?php endif ?>