How to exclude child categories from multiple parents in WP_Query?


I have some code

        $exclude_category = [10];

        $company_category_parents = get_categories( array('child_of' => 5) );
        foreach ($company_category_parents as $company_category_child) {
            array_push($exclude_category, $company_category_child->cat_ID);

        $interviews_category_parents = get_categories( array('child_of' => 58) );
        foreach ($interviews_category_parents as $interviews_category_child) {
            array_push($exclude_category, $interviews_category_child->cat_ID);

        $recent_news_main_query = new WP_Query( array(
            'posts_per_page' => 3,
            'category__not_in' =>  $exclude_category,
        ) );

Category with id = 10 single category. Categories with id = 5 and id = 58 have children categories and they are actually parent categories id. As you can see in my code I’m making 2 foreach loops and I’m pushing data to array. It’s quite good for now but it can be more than 2 categories with childrens in future. So my question is, is it any way to make it more usable with more than 2 ids? I want to type single category ID in one place and parent categories ID in second place and in final result I want to have one array with single ids and children categories ids. So when parent category with ID 5 have children categories with ids 1, 2, 3 my final array should have 10, 1, 2, 3 How can I do this?

, , MMPL1 2 years 2020-08-27T09:10:23-05:00 0 Answers 59 views 0

Leave an answer