0

Is there a way to add a custom variable to the queried object?

if (is_page()) {
    $q = get_queried_object();
    $term_id = $q->term_id;
}

Here's some background on my setup.

I have a page with a custom WP_Query that outputs all posts from a particular taxonomy. I need to save the taxonomy 'term_id' somewhere so other areas of my code can know which category in the custom loop is currently being displayed.

Right now I am using 'update_post_meta' to store a custom field to the page which holds this value. I don't want to use a custom field though. So I am looking for the best alternate solution.

if ($meta_term_id > -1) {
    update_post_meta( get_queried_object()->ID, 'term_id', $meta_term_id);
}

// Build Query
$custom_query = new WP_Query($args);

I have looked into add_query_vars but I don't want to add an url param to every page.

www.mydomain.com/custom-page/?term_id='38';

I'm hoping there is a way to attach data to the page object which will have the term_id I need.

***Update****

I didn't figure out a way to add custom data to the post object like I had hoped but did find a solution to creating custom post meta data but not showing the custom field on the page edit screen. Just need to prepend the post meta data name with an underscore.

update_post_meta( get_queried_object()->ID, '_term_id', $meta_term_id);
0

I updated my question with a partial answer to this problem. By adding an underscore '_' before the name of the meta field it allows you to add meta data without it creating an editable custom field on the page edit screen.

update_post_meta( get_queried_object()->ID, '_term_id', $meta_term_id);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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