functions - allow only one post in specific category

admin2025-06-03  3

I have a category called "best post". When the editor selects this category in a post and publishes the page, a PHP routine must check if other posts have this category, and if so, this category must be deleted from all posts except the current page...

I have a category called "best post". When the editor selects this category in a post and publishes the page, a PHP routine must check if other posts have this category, and if so, this category must be deleted from all posts except the current page...

Share Improve this question asked Feb 12, 2019 at 15:26 frenchman100frenchman100 153 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 3

After the post save (using save_post hook) you check if the saved post has your "unique" category, and if so remove the category from the other posts, keeping the one you just saved.


add_action( 'save_post', 'set_post_unique_category', 10,3 );

function set_post_unique_category( $post_id, $savedPost, $update ) {

    // Only set for post_type = post
    if ( 'post' !== $savedPost->post_type ) {
        return;
    }

    // Check if post has your desired category
    if ( ! has_category('best-post', $savedPost) ){ //use your category slug
        return;
    }

    // Get the best-post category term by its slug
    $term = get_term_by( 'slug', 'best-post', 'category' );

    //Now let's find the other posts with your category
    $args = array( 'category' => $term->term_id, 'post_type' =>  'post' );  //set the arguments for the query
    $postsList = get_posts( $args );  

    foreach ($postsList as $post) { //Remove the category from the found posts
         if ($post->ID == $post_id ) //but skip the just saved post
              continue;

         wp_remove_object_terms( $post->ID, 'best-post', 'category' );
    }



}

I haven't tested it so you could encounter syntax errors or wrong property names, but the logic should be fine, at least to get you an idea of what you should do. A good google search plus a wordpress codex stroll are always your friends ;)

转载请注明原文地址:http://conceptsofalgorithm.com/Algorithm/1748914282a314771.html

最新回复(0)