Steve
Steve

Reputation: 4898

Getting page ID in a template that has no loop

I have a form that collects data on a product and then puts the data into the wp_posts table and wp_postmeta table. I can build a permalink around the ID and if I then do a wp_redirect to this permalink WordPress should try to display the page.

The page's template is called listing.php, and it has no Loop. Its only purpose is to display these product pages by placing the data in the wp_posts table and wp_postmeta table into various divs. But I'm wondering how the template can get the ID of the page it's building so it can access the wp_posts table and wp_postmeta table. I'd like to do something like $meta = get_post_meta( get_the_ID() ) but the codex says you can only use get_the_ID() in the Loop and I don't have one of those. So how should I be doing this?

Thanks

Upvotes: 0

Views: 1710

Answers (2)

Pieter Goosen
Pieter Goosen

Reputation: 9941

The most sound and reliable way to get the page ID of the current page is to make use og the queried object. The two functions get_queried_object() and get_queried_object_id() will hold the info of the current page (on category, tag, taxonomy and author pages it will hold the current category, tag, term and author info respectively)

To get the page id, simply use

$page_id = get_queried_object_id();
echo $page_id;

Upvotes: 1

Harry Manback
Harry Manback

Reputation: 417

You can grab the post id from the global $post variable.

global $post; echo $post->ID;

Upvotes: 0

Related Questions