bojo
bojo

Reputation: 399

Wordpress Page ID not Post ID

Is there any way to get ID of the current page which shows posts in loop? I need to get this ID in header.php.

<?php
     $query = new WP_Query( array('post_type' => 'portfolio') );
     while ( $query->have_posts() ) : 
          $query->the_post(); 
 ?>                           
 //here I added posts
 <?php endwhile; ?>

Upvotes: 3

Views: 3753

Answers (3)

MikeJones
MikeJones

Reputation: 1

Try get_queried_object(). It returns the WP_Post object which is from the queried page. From there you can get the id using

get_queried_object()->ID.

Upvotes: 0

I&#39;m Joe Too
I&#39;m Joe Too

Reputation: 5840

It depends on where you want to get this ID. If you are trying to get it on the page that you have set to show posts (ie, a page set as your "blog"), you need to use:

$page_id = get_option( 'page_for_posts' );

If you want to get this on any other page and you're using a custom query, you can get this (before your custom loop) using:

global $post;
$page_id = $post->ID;

Because you're using WP_Query and the_post(), you'll want to reset the post data after your custom loop with wp_reset_postdata(); to use template tags again. I suspect that's where your problem is - you're hijacking the template tags with your custom loop and not resetting them.

Upvotes: 1

user319940
user319940

Reputation: 3317

The get_the_ID() method is probably what you need:

 <?php get_the_ID(); ?> 

http://codex.wordpress.org/Function_Reference/get_the_ID

Upvotes: 0

Related Questions