Wordpress页面ID不是Post ID


Wordpress Page ID not Post ID

有没有办法获得当前页面的ID,该页面显示循环中的帖子?我需要在header.php.中获取此ID

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

这取决于你想在哪里获得这个ID。如果你想在你设置为显示帖子的页面上获得它(即,一个设置为"博客"的页面),你需要使用:

$page_id = get_option( 'page_for_posts' );

如果你想在任何其他页面上获得它,并且你正在使用自定义查询,你可以使用(在自定义循环之前)获得它

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

因为您使用的是WP_Query和the_post(),所以您需要在使用wp_reset_postdata();的自定义循环之后重置post数据,以便再次使用模板标记。我怀疑这就是你的问题所在——你用自定义循环劫持了模板标签,却没有重置它们。

get_The_ID()方法可能正是您所需要的:

 <?php get_the_ID(); ?> 

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