Skip to content
Advertisement

How can I check if a TERM is assigned with a POST using two parameters term slug and post ID?

I need to check whether a post has been assigned with a term but I do not have information about the taxonomy of that term as it could be any taxonomy present in my site.

Advertisement

Answer

You can have a custom function to return terms for all taxonomies:

/**
 * Get terms for all taxonomies
 *
 * @see get_object_taxonomies()
 */
function yourprefix_all_axonomies_terms($post_id) {
    $post       = get_post( $post_id );
    $post_type  = $post->post_type;
    $taxonomies = get_object_taxonomies( $post_type );
    $out        = [ ];

    foreach ( $taxonomies as $taxonomy_slug ){

        // Get the terms related to post.
        $terms = get_the_terms( $post->ID, $taxonomy_slug );

        if ( ! empty( $terms ) ) {
            foreach ( $terms as $term ) {
                $out[] = $term->slug;
            }
        }
    }
    return $out
}

Then use it like:

if (in_array($term_looked_for, yourprefix_all_axonomies_terms( $post->ID ) ) {
// do your thing
}
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement