Using WordPress ‘get_objects_in_term()’ PHP function

The get_objects_in_term() WordPress PHP function retrieves object IDs of valid taxonomy and term.

Usage

get_objects_in_term($term_ids, $taxonomies, $args = array());

Parameters

  • $term_ids (int|array): Term ID or array of term IDs of terms that will be used.
  • $taxonomies (string|array): String of taxonomy name or array of string values of taxonomy names.
  • $args (array|string, Optional): Change the order of the object IDs, either ASC or DESC. Default: array()

More information

See WordPress Developer Resources: get_objects_in_term

Examples

Retrieve object IDs of posts in a category

// Get object IDs of posts in category with ID 5
$term_id = 5;
$taxonomy = 'category';
$object_ids = get_objects_in_term($term_id, $taxonomy);

// Output the object IDs
foreach ($object_ids as $object_id) {
    echo "Post ID: " . $object_id . "<br>";
}

Retrieve object IDs of posts in multiple categories

// Get object IDs of posts in categories with IDs 5 and 7
$term_ids = array(5, 7);
$taxonomy = 'category';
$object_ids = get_objects_in_term($term_ids, $taxonomy);

// Output the object IDs
foreach ($object_ids as $object_id) {
    echo "Post ID: " . $object_id . "<br>";
}

Retrieve object IDs of posts with a custom taxonomy

// Get object IDs of posts with custom taxonomy 'location' and term ID 9
$term_id = 9;
$taxonomy = 'location';
$object_ids = get_objects_in_term($term_id, $taxonomy);

// Output the object IDs
foreach ($object_ids as $object_id) {
    echo "Post ID: " . $object_id . "<br>";
}

Retrieve object IDs of posts sorted in descending order

// Get object IDs of posts in category with ID 5, sorted in descending order
$term_id = 5;
$taxonomy = 'category';
$args = array('order' => 'DESC');
$object_ids = get_objects_in_term($term_id, $taxonomy, $args);

// Output the object IDs
foreach ($object_ids as $object_id) {
    echo "Post ID: " . $object_id . "<br>";
}

Retrieve object IDs of posts in multiple taxonomies

// Get object IDs of posts in category with ID 5 and custom taxonomy 'location' with term ID 9
$term_ids = array(5, 9);
$taxonomies = array('category', 'location');
$object_ids = get_objects_in_term($term_ids, $taxonomies);

// Output the object IDs
foreach ($object_ids as $object_id) {
    echo "Post ID: " . $object_id . "<br>";
}