Getting category before saving post

I am using the filter “wp_insert_post_data” to decide what to save to the database. I need to know which category has been picked before saving the post.

How can I get to know the category that has been picked while using that filter? Is there a $_POST[“category”] like variable or category object accessible at this phase?

Related posts

1 comment

  1. Yes, and you’re quite close to it. Just use the $postarr parameter of this filter:

    add_filter( 'wp_insert_post_data' , 'wpse128138_wp_insert_post_data', 99, 2 );
    function wpse128138_wp_insert_post_data( $data, $postarr ) {
    
        // run this only for posts
        if ( 'post' != $postarr['post_type'] )
            return $data;
    
        foreach( $postarr['post_category'] as $category_id ) {
            if ( is_wp_error( $category = get_category( $category_id ) ) )
                continue; // invalid category, just pass
    
            // and here you can safely use the $category object
        }
    
        return $data;
    }
    

Comments are closed.