YARPP: How To Exclude Posts Or Categories

YARPPThe related posts plugin ‘YARPP’ from Mitcho is a fine piece of work, and worth supporting.

But as with many WordPress plugins, sooner or later you come across something you need to do with it that the author hasn’t considered yet, or had time to add, or been nagged enough to provide 😉

And so we found ourselves on a project wanting to exclude certain posts from displaying any related posts.

Now, we’re NOT talking about excluding those posts from appearing in the pool of related posts. You can already stop posts showing up as a related post already using the Disallow By Tag and Disallow By Category features built in to YARPP. These options are hidden by default though, so you need to click ‘Screen Options’ at the top and enable the “The Pool” if you don’t see them:-

yarpp-screen-options

Stopping A Post Showing Related Links

OK, so getting back on track. Here’s the solution we used to exclude the related posts from appearing where we didn’t want them.

The key to our fix was use of the WordPress function has_tag(), which is one of the many WordPress conditional tags. You might find is_category() better suits your purpose.

This may not work for every scenario, but you may be able to adapt your approach to this solution anyway.

So first of all you need to insert your own code into the WordPress template, so you will need to turn off the ‘Automatically display’ option (otherwise you’ll end up with two lots of related posts in the page!).

yarpp automatic

Now you can simply insert the YARPP code manually, along with your conditional statement. So you can edit the Single Post template (single.php) and add something like this where you want the related posts to appear in the page:-

<?php if (! has_tag('tag-slug-here')) { related_posts(); } ?>

A Few Minor Warnings…

Unless this is a totally custom theme that you have sole control over, you should be using a child theme. So copy single.php to your child theme folder before editing (if not already there). If you’re not sure what a child theme is or why to use one, this page at WordPress.org will help.

You should probably also wrap your statement in an if(function_exists('related_posts'). Otherwise if anyone ever disables the YARPP plugin, WordPress will error (because the related_posts function would then no longer exist – this catches that).

This solution works just fine for a more minor purpose such as this. But if you’re driving anything critical from the conditionals, bear in mind that your code could be easily foiled by somebody simply making a small change to the name or slug of the tag or category.

The is_category() function can be made a bit more robust by specifying a category ID instead of using the name or slug. This may work for has_tag() too, but it isn’t documented and we didn’t test it.

Leave a Reply

Your email address will not be published. Required fields are marked *