How to Exclude Posts with a Certain Tag from the WordPress Loop

Home » Snippets » How to Exclude Posts with a Certain Tag from the WordPress Loop
0

Created with:

Visibility: 

public

Creator: WPTurbo Team

Customize with WPTurbo AI
X

Add Snippet To Project

New Project
Add To Existing Project

Are you tired of seeing posts with a certain tag appearing in your WordPress loop? Maybe you want to exclude posts with a specific tag from being displayed on your website. Fortunately, there is a simple solution for this. In this article, we will guide you through the process of excluding posts with a certain tag from your loop, helping you to have more control over the content displayed on your WordPress website.

					function wpturbo_exclude_posts_with_tag($query) {
    if ($query->is_main_query() && !is_admin()) {
        $tag_id = get_term_by('name', 'tag_name', 'post_tag')->term_id;
        $query->set('tag__not_in', $tag_id);
    }
}
add_action('pre_get_posts', 'wpturbo_exclude_posts_with_tag');
				

The code snippet provided allows excluding posts with a certain tag from the loop in WordPress. This can be useful if you want to filter out specific posts with a particular tag from being displayed on your website.

To achieve this, we create a new function called wpturbo_exclude_posts_with_tag() and hook it into the pre_get_posts action. This action is triggered before the query is executed, giving us a chance to modify the query parameters.

The first line of the function checks if the current query is the main query and not from the admin area. This ensures that the code only applies to the main content loop on the front-end of the website and not any other queries or admin pages.

Next, we use the get_term_by() function to retrieve the term ID of the tag we want to exclude. We pass in the tag name (‘tag_name’) and the taxonomy (‘post_tag’) to specify that we are looking for a tag term.

Once we have the tag ID, we update the query parameter using the set() method of the $query object. We set the tag__not_in parameter to the tag ID, which excludes posts with that tag from the query results.

By modifying the query in this way, the excluded posts will not be included in the loop and will not be displayed on your website.

It’s important to note that you need to replace 'tag_name' with the actual name of the tag that you want to exclude. Additionally, make sure to update the hook used in the add_action() function if you want to target a different action.

With this code snippet, you can easily exclude posts with a specific tag from being displayed in the loop on your WordPress website.

Register an account to save your snippets or go Pro to get more features.