Wordpress function to get term or post object by id

by Daniel   Last Updated May 12, 2018 12:08 PM

Currently to differentiate between post and term objects I use short piece of code:

$object = get_post($id);

if ( ! $object ) {
    $object = get_term($id);
}
print_r($object);

Is there a function which returns post object or term object with given id without using above if statement?

Best regards, Dan.

PS, I need it for WP ajax calls.



Answers 1


get_queried_object() will get the currently queried 'thing' from the main query as an object. That could be a WP_Post, WP_Term, or WP_Post_Type (for post type archives) object, but that's not quite what you're asking for and wouldn't be useful in AJAX.

There isn't a function for exactly what you're asking for but it probably wouldn't be advisable anyway. Terms and Posts are stored in separate tables, so there could easily be terms and posts with the same ID. Sure you could get the post if it exists or fall back to the term, as in your existing code, but what if you're expecting the term for a given ID but there's a Customiser revision with the same ID? That's not particularly helpful and probably not what you were requesting.

If you're sending an ID via AJAX and want the appropriate object in the callback function then the best approach would be to also send the expected object type via AJAX and retrieve the appropriate function based on that.

Jacob Peattie
Jacob Peattie
May 12, 2018 12:07 PM

Related Questions


Why does wp_remove_object_terms not work?

Updated April 01, 2018 06:08 AM

Filtering WP_Query Dynamically on the Front-End

Updated November 07, 2017 07:08 AM


return only the first two terms of custom post

Updated October 11, 2017 06:08 AM