Posted on

Excluding posts by taxonomy

Relevanssi has a category exclusion feature built in, but that only works for basic categories and not any other taxonomies. You can use tax_query to restrict the searches as well, but that’s more complicated than adjusting the setting in Relevanssi settings.

However, if the exclusion is permanent, it’s best done in the indexing level. That way the excluded posts are not taking space in the database. It’s really simple. Just add this code to your theme functions.php:

add_filter('relevanssi_do_not_index', 'rlv_exclude_cat', 10, 2);
function rlv_exclude_cat($exclude, $post_id) {
    if (has_term( TERM, TAXONOMY, $post_id )) $exclude = true;
    return $exclude;
}

where TERM is term name, slug or ID of the term you want to exclude, or an array if you plenty and TAXONOMY is the name of the taxonomy (for example “product_cat”, if you’re working with WooCommerce product categories). Then rebuild the index, and you shouldn’t see anything from the excluded category in the results.

8 comments Excluding posts by taxonomy

  1. I tried this. But, I’m getting a PHP Warning error.

    Missing argument 2 for rlv_exclude_cat().

    Could you tell me how to fix it?

    Thanks.

      1. Hi,

        Sorry to re-open this topic, but the code you suggested doesn’t work in my website using woocommerce (Up to now the website is localhost).

        The exact code that I had in my childtheme is :

        add_filter(‘relevanssi_do_not_index’, ‘rlv_exclude_cat’, 10, 2);
        function rlv_exclude_cat($exclude, $post_id) {
        if (has_term( “product_tag”,”product_cat”, $post_id )) $exclude = true;
        return $exclude;
        }

        The setting in the plugin is shown in the picture attached.

        I can’t figure it out.

        Thank you to help me,
        Bruno

        1. What exactly are you trying to do here? Are you trying to exclude posts that have the term “product_tag” from the “product_cat” taxonomy? Because that’s what you’re doing now. If that’s correct, then I’d check if you’re using Relevanssi in the first place.

          1. Hi Mikko,

            I have :
            product …….. post_type=product
            category …… taxonomy=product_cat
            tag …………… taxonomy=product_tag

            I wonder :
            exclude ………. product_cat = 6
            exclude ………. product_tag = 14

            Regards,
            Bruno

          2. Use:

            if (has_term( 6,”product_cat”, $post_id )) $exclude = true;
            if (has_term( 14,”product_tag”, $post_id )) $exclude = true;

            That should work much better.

          3. Hi Miko,

            Thank you for your support (a sunday, that is great!!!).
            I will be able to try this code later in the day.
            I will inform you.

            Bruno

Leave a Reply

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