Question

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.

Was it helpful?

Solution

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 );
        break;
    case 'term':
        $object = get_term( $id );
        break;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top