Show Related Posts by Primary Category Only

This tutorial includes the code which enables you to display related posts in the same category when that category is set as your primary category using the Primary Category setting in the category box on single post edit screens.

Note : Requires the installation of the Yoast SEO plugin to add the primary category option.

This primary category setting is used when you assign a post multiple categories and want to set a primary.

Uses the WPSEO_Primary_Term class in Yoast SEO.

Demo Video

Tested using the genesis Sample child them by StudioPress however will work in any Genesis child theme.

Installation Steps

  1. # Copy and paste the PHP code ( without the opening PHP tag ) to the end of your child themes functions file.
  2.  

  3. # Copy & paste the CSS from the style.css file to the end of your child themes style sheet and clear caching.
  4.  

  5. # Install the Yoast SEO plugin and select the primary category for posts assigned multiple categories.
  6.  

Download Folder

Related Posts


Comments

7 responses to “Show Related Posts by Primary Category Only”

  1. Jonathon Fowler Avatar
    Jonathon Fowler

    One more question please Brad…if I view the post on a moblie device, the thumbnail featured images don’t display, only the link anchor text appears for each related post. How do I get the thumbnail to remain, even on mobile devices?

    1. Remove this CSS rule from your style.css file.

      [code]
      .grid-image {
      display: none;
      }
      [/code]

      1. Jonathon Fowler Avatar
        Jonathon Fowler

        Great, that worked perfectly. Thanks man!

  2. Jonathon Fowler Avatar
    Jonathon Fowler

    Hi Brad, I installed this and it works, thank you.

    How do I get it to only display the three latest posts within the Primary category? At the moment it displays 3 random posts that change each time you refresh the page.

    Thanks, Jonathon

    1. Jonathon Fowler Avatar
      Jonathon Fowler

      Sorted, I changed the ‘rand’ within the functions file to ‘date’. Thanks, works great!

  3. Jonathon Fowler Avatar
    Jonathon Fowler

    I have a few different categories on my blog.

    For each blog post, I only use one category.

    Will this enable displaying related posts only from the same category?

    At the moment my blog shows the 3 most recent posts regardless of category.

Leave a Reply

Join 5000+ Followers

Get The Latest Free & Premium Tutorials Delivered The Second They’re Published.