-1

I am very new in WordPress development and I have the folglowing problem.

I use this function (declared into the functions.php file of my theme) to modify the main query in such a way that the post having a specific tag are not displayed in my homepage:

function exclude_featured_tag_and_legacy_posts( $query ) {

    $tagId = get_tag_ID("featured");
    //echo("Featured Tag Id: + $tagId");

    if ( $query->is_home() && $query->is_main_query() ) {
        //$query->set( 'tag__not_in', 'array(ID OF THE FEATURED TAG)' );

        $query->set( 'tag__not_in', array($tagId));
    }

}
add_action( 'pre_get_posts', 'exclude_featured_tag' );

As you can see this function is executed after the main query creation but before its executions and it modify the main query for the exclusion of the posts that have the tag named featured

Ok, it seems work fine. Now my problem is. How can I further modify my main query so that is also excluded the posts belonging to a specific category?

So I want that is excluded both the posts having the featured tag and the posts belonging to the legacy category.

Can you help me?

1

pre_get_posts and WP_Query uses the exact same parameters, so if you need to know which parameters you can use with pre_get_posts, simply visit the WP_Query page in the codex.

There is another trick which you can use to get all the parameters (query_vars) you can use. Just add this on the page that you need to get the query_vars from, refresh the page, and this function will print out all the query_vars you can use with pre_get_posts and WP_Query

<?php global $wp_query; ?>
    <pre><?php var_dump($wp_query->query_vars); ?></pre>
<?php

To exclude a category, you can either use cat or category__not_in. Both take category ID's, cat take integers and category__not_in an array. So one of the following will do in your function

$query->set( 'category__not_in', array(ARRAY OF CAT ID's));

OR

$query->set( 'cat', 'ID's OF CAT');

You just have to make sure, your callback function in add_action and your actual function name does not match. exclude_featured_tag must be exclude_featured_tag_and_legacy_posts

  • Just checking in to see what is the status of your problem, is it resolved yet. If my answer solved your issue, please consider accepting my answer. If mine did not meet your standards and you manage to resolve this issue yourself, please consider posting and accepting your own answer. Would be nice to know how you've resolved this :-). If you are still having this problem, feel free to post a comment to my answer explaining where my answer are lacking. Many thanks – Pieter Goosen Sep 7 '14 at 12:11
0

Please check the category parameters in the WP_Query documentation.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.