Retrieves the terms for a post.
Parameters
$post_id
intoptional- The Post ID. Does not default to the ID of the global $post. Default 0.
$taxonomy
string|string[]optional- The taxonomy slug or array of slugs for which to retrieve terms. Default
'post_tag'
.Default:
'post_tag'
$args
arrayoptional- Term query parameters. See WP_Term_Query::__construct() for supported arguments.
fields
stringTerm fields to retrieve. Default'all'
.
Default:
array()
Source
* is 'ids', an array of category IDs. If `$fields` is 'names', an array of category names.
* WP_Error object if 'category' taxonomy doesn't exist.
*/
function wp_get_post_categories( $post_id = 0, $args = array() ) {
$post_id = (int) $post_id;
$defaults = array( 'fields' => 'ids' );
$args = wp_parse_args( $args, $defaults );
$cats = wp_get_object_terms( $post_id, 'category', $args );
Changelog
Version | Description |
---|---|
2.8.0 | Introduced. |
The difference between this function and
get_the_terms()
is that this function’s results are not cached (thus, it’ll hit the database every time its called).get_the_terms()
does not allow the third parameter:$args
.Examples
Get term category to only run function if the post (CPT) has that category:
Use curly brackets recommended but not needed on one expression of foreach
Get all taxonomy slug of a post
You can get the taxonomy terms HTML using this function am_get_post_term