get_objects_in_term()
Retrieve object_ids of valid taxonomy and term.
The strings of $taxonomies must exist before this function will continue. On failure of finding a valid taxonomy, it will return a WP_Error.
The $terms aren't checked the same as $taxonomies, but still need to exist for object IDs to be returned.
It is possible to change the order that object IDs are returned by using $args with either ASC or DESC array. The value should be in the key named 'order'.
No Hooks.
Return
String[]|WP_Error
. An array of object IDs as numeric strings on success, WP_Error if the taxonomy does not exist.
Usage
get_objects_in_term( $term_ids, $taxonomies, $args );
- $term_ids(int|int[]) (required)
- Term ID or array of term IDs of terms that will be used.
- $taxonomies(string|string[]) (required)
- String of taxonomy name or Array of string values of taxonomy names.
- $args(array|string)
Change the order of the object IDs.
Default: array()
- order(string)
Order to retrieve terms. Accepts 'ASC' or 'DESC'.
Default: 'ASC'
- order(string)
Examples
#1 Get the ID of all posts from the category
Here we get the IDs of the posts from category 33:
$post_ids = get_objects_in_term( 33, 'category' ); print_r( $post_ids ); /* Array ( [0] => 72 [1] => 372 [2] => 800 ) */
#2 Get the IDs of all posts from several taxonomies and their elements
Here 33 is the 'category' tax element, and 12 is the 'post_tag' tax element:
$objects = get_objects_in_term( [ 33, 12 ], [ 'category', 'post_tag' ] ); print_r( $objects ); /* Array ( [0] => 72 [1] => 372 [2] => 800 [3] => 2818 [4] => 2971 [5] => 3755 ) */
#3 Checking the return value
$objects = get_objects_in_term( [ 33, 12 ], [ 'category', 'post_tag' ] ); if( is_wp_error( $objects ) ){ echo 'The taxonomy is incorrect'; } elseif( ! $objects ){ echo 'No objects'; } else { echo 'there are objects!'; print_r( $objects ); }
#4 List of all post tags from the specified category
This example shows how to get a list of all post tags that are in a specified category (in this case, the current category) with the least amount of code.
if( is_category() ){ $term_id = get_queried_object_id(); // the id of the current category // collect the IDs of all nested categories $term_ids = get_term_children( $term_id, 'category' ); array_push( $term_ids, $term_id ); $post_ids = get_objects_in_term( $term_ids, 'category' ); if ( $post_ids && ! is_wp_error($post_ids) ) { $tags = wp_get_object_terms( $post_ids, 'post_tag' ); if ( $tags && ! is_wp_error( $tags ) ){ $list = []; foreach( $tags as $tag ){ $list[] = '<a href="'. get_term_link( $tag, 'post_tag') .'">'. esc_html( $tag->name ) .'</a>'; } echo ' <ul> <li>'. implode( "</li>\n<li>", $list ) .'</li> </ul> '; } } }
Notes
- Global. wpdb. $wpdb WordPress database abstraction object.
Changelog
Since 2.3.0 | Introduced. |