1

I am trying to get page id from my template-contact.php like this :

global $post;
echo $post->ID;

It's showing 85 but page id is 96, I want to get id because I want to fetch meta of current page.

Here is my template code.

<?php /* Template Name: Contact Page */ ?>

<?php get_header() ?>
<?php 

global $post;
echo get_post_meta($post->ID, 'contact_page', true);


?>
<?php get_footer() ?>

Please help

  • That code is correct (although I'd use get_the_ID() to do the same). Where in your template are you loading it exactly? Are you sure you're calling that from within the loop? – swissspidy Feb 19 '18 at 10:51
  • I have edited the question and added my template code, how to get meta information for the page, in $post->ID i am getting a post's id instead of current page's id – Anand Siddharth Feb 19 '18 at 11:24
  • got it, I just had to write the_post() before global $post. – Anand Siddharth Feb 19 '18 at 11:32
2

To get the ID of the page being queried from outside the loop or before the global post object has been set, use get_queried_object_id().

<?php
/**
 * Template Name: Contact Page 
 */

get_header();
?>

<?php
$page_id = get_queried_object_id();
echo get_post_meta( $page_id, 'contact_page', true);
?>

<?php get_footer() ?>
| improve this answer | |

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.