WordPress widget for recent posts in same category

WordPress widget for recent posts in same category

Working on a site update recently, I needed to provide secondary navigation to recent posts by category. The theme my client was using provided no such navigation, but did have at least a dozen spaces for widgets. I created a child theme and put code similar to the following in functions.php, but one could also wrap similar code in a plug-in. The code below generates a dynamic widget that displays

  • recent posts sharing a same category when viewed on a single post page,
  • recent posts of in a category when viewed on a category archive page,
  • or recent posts of any category when viewed on any other page.

It also changes the widget title appropriately to “Recent and Related” or just “Recent Posts”.

View the project on GitHub