简体   繁体   中英

Check WordPress posts category - leave posts only in main, remove from other using PHP

I am trying to execute this: I have posts in multiple catogories, one category is mutual for all posts, that is "Business" category, all others are irrelevant, so I want to remove all posts which are in "Business" category from all other categories. I created this code:

<?php
$posts = get_posts(array(
    'category' => 'Business',
));

foreach($posts as $post) {

    $categories = wp_get_post_categories($post->ID);

    if (in_array('Business', $categories) && count($categories) > 1) {
        wp_set_post_categories($post->ID, array(
            'Business',
        ));
    }
}

This code should go through all posts in "Business" category, and for any posts which is NOT ONLY in "Business" category - that posts should be removed from all other categories except "Business". But...code does not work, for some reason. There is no PHP error, just - not working.

Any help appreciated...

This is working code which checks for all posts within category, using category ID and if founds posts which are inside target category, but also - they are in other categories as well - removes posts from all other categories, except the target category: in example cat ID is 6:

    <?php
    function remove_posts_from_other_categories_retroactively() {
    
      $posts = get_posts(array('category' => 6, 'numberposts' => -1));
      
      foreach ($posts as $post) {
        wp_set_post_categories($post->ID, array(6));
      }
    }
    
    add_action('plugins_loaded', 'remove_posts_from_other_categories_retroactively');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM