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

$object = get_post($id);

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

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.

1 Answer 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 I don't think that's quite what you're asking for and wouldn't be useful in AJAX.

Other than that 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. Not to mention that WP_Term and WP_Post have different properties and represent entirely different things, meaning they're not interchangeable, which makes the utility of such a function dubious.

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.

$id = $_GET['id'];
$object_type = $_GET['object_type'];

switch ( $object_type ) {
    case 'post':
        $object = get_post( $id );
    case 'term':
        $object = get_term( $id );
  • I thought about get_queried_object() but it doesn't accept any arguments therefore it's not possible to use it with ID already supplied. Unfortunately I'm restricted only to menu items, that's where I get my IDs from (via get_post_meta( $object_id, '_menu_item_object_id', true );). I haven't noticed, that every menu item has class representing type of object behind that particular menu item (i.e. menu-item-type-taxonomy). I wrote simple JS regex to retrieve the type and I can use your example with ease now. Thank you!
    – Daniel
    May 12, 2018 at 14:27
  • Menu items have their type stored as the _menu_item_type meta. post_type for posts and taxonomy for terms. May 12, 2018 at 16:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.