WordPress: How to get new post tags

395 views Asked by At

I'm trying to get the list of post tags after saving it.

when the post is saved the first time I get an empty array, but when saved the second time (edited) the tags appears correctly,

here is the code I'm using to get the tags:

add_action( 'save_post', 'collect_tags' );
// ...
function collect_tags($postId){
    $terms = get_object_term_cache( $postId, 'post_tag' );
    if ( false === $terms ) {
        $terms = wp_get_object_terms( $postId, 'post_tag' );
    }
    if( empty( $terms )) {
        $terms = wp_get_post_tags( $postId );
    }
    return $terms;
}

Could anybody please point me to where my mistake is?

I'm using WordPress version 4.7

1

There are 1 answers

0
metad00r On

Try

function collect_tags( $post_id, $post, $update ) {
    $terms = get_object_term_cache( $post_id, 'post_tag' );
    if ( false === $terms ) {
        $terms = wp_get_object_terms( $post_id, 'post_tag' );
    }
    if( empty( $terms )) {
        $terms = wp_get_post_tags( $post_id );
    }

    // --- TEST ---
    $tags = wp_get_post_tags( $post_id );
    print_r( $tags );
    // --- END  ---

    return $terms;
}
add_action( 'wp_insert_post', 'collect_tags', 10, 3 );