Help with “Recent Posts” Loop that is specific to a topic

Put this in your sidebar template where you want the listing to show up. Alternatively, you could use a plugin that allows you to run php in widgets and then place directly in a widget box, but that’s not always wise.

<?php
$categories = get_the_category();
$category = $categories[0];
$category_id = $category->cat_ID;
$args = array('category__in' => $category_id, 'posts_per_page' => '5');
$recent_in_cat = new WP_Query( $args );if ( $recent_in_cat->have_posts() ) {while ( $recent_in_cat->have_posts() ) {$recent_in_cat->the_post();
?>
<p><a href="https://wordpress.stackexchange.com/questions/192761/<?php the_permalink(); ?>"><?php the_title(); ?></a></p>
<? php
}} wp_reset_postdata();
?>

Note that the start and end tags <?php and ?> should only be there unless you’re already in the middle of (unclosed) php code, else skip them.