wp_get_object_terms returns only Uncategorized on first publish

Question

I would like to get all assigned categories of a post once it’s published with the save_post hook:

add_action( 'save_post', function( $post_id, $post, $update = null ) {

    if ( 'publish' == $post->post_status ) {;
        $categories = wp_get_object_terms( $post_id, 'category' );

        ...
    }

},10 ,3 );

When I save the post for the first time $categories contain always the "Uncategorized" category.
Once I update the post (without changing any taxonomy) it contains the selected categories.

$categories on first save:

Array(

[0] => WP_Term Object
    (
        [term_id] => 1
        [name] => Uncategorized
        [slug] => uncategorized
        [term_group] => 0
        [term_taxonomy_id] => 1
        [taxonomy] => category
        [description] => 
        [parent] => 0
        [count] => 2
        [filter] => raw
    )

)

$categories on post update:

Array (

[0] => WP_Term Object
    (
        [term_id] => 2
        [name] => My Category
        [slug] => my-category
        [term_group] => 0
        [term_taxonomy_id] => 2
        [taxonomy] => category
        [description] => 
        [parent] => 0
        [count] => 1
        [filter] => raw
    )

)

I’m sure this is not the expected behavior but I can repeat this with every version of the block editor. WP 4.9 works as expected and shows all selected categories even on the first publish.

0
Xaver 5 months 2020-12-29T09:10:21-05:00 0 Answers 3 views 0

Leave an answer

Browse
Browse