0

I am trying to use pre_get_posts to exclude categories from posting to the homepage. If I do it like so it works just fine

 $query->set( 'cat', '-13,-7,-19,-12,-24,-21,-14');

that is hard coded in. I am building a custom admin that lists the categories in the admin menu. So now I want to use the id's that get selected in the admin menu. So I have assigned my id's to a variable and when I var_dump the variable, this is what I get

 string(2) "13"
 string(1) "7"
 string(2) "19"
 string(2) "12"
 string(2) "24"
 string(2) "21"
 string(2) "14"

So all those are assigned to the variable $category and so I thought I could do this

 $category = get_option( 'excludecats' );
 foreach( $category as $exclude ){
    $query->set( 'cat', '-'.$exclude );
 }

when I view the source, I expect there to be 1987 lines of code but what I end up with is 3117 lines of code trying to use the foreach to exclude them. What am I doing wrong?

0

try to implode $category with "," as a glue. Mentioned code in each foreach run rewtites the cat variable of $query.

$query->set('cat', implode(',', $category));
1

When you use the pre_get_posts action you have access to alter any of the query_vars using the set method.

According to the codex documentation linked above you can use your array and set it as the value of the 'category__not_in' query_var.

$query->set( 'category__not_in', $category );

0

This is the final code I went with

 function wpa83038_posts_and_pages_on_home( $query ) {
if ( $query->is_home() && $query->is_main_query() ) {
    $query->set( 'post_type', array( 'post', 'page') );
    //GETTING THE OPTION FROM TEH ADMIN TO EXCLUDE THE BLOG POSTS FROM THE HOMEPAGE.
            //using option tree for the WordPress admin area
    if( function_exists( 'ot_get_option' )){
        $category = ot_get_option( 'excludecats' );

        $exclude = implode(",-",$category);
        $exclude = '-'.$exclude;
        $query->set( 'cat', $exclude);
    }
  }
}

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.