it's been a while since I used wordpress and I am trying to us e advanced custom fields, I am trying to output the post ID inside a loop on a page, so i can use get_field to output the post contents. Ths $post->ID gives me the page id not the post id so thr wrong number is being outputted, how do I get the post ID?

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

                    <?php $current_id = $post->ID ?>

   <?php echo $current_id ?>

            <h1><?php the_field('titleFart', $current_id); ?></h1>

        <?php endwhile; // end of the loop. ?>

<?php endif; ?>
  • how are you querying for posts in the page?
    – Milo
    May 13, 2014 at 19:37
  • If you echo get_the_id(), are the numbers the same? May 13, 2014 at 19:38
  • yes they are both the page id not the post id May 13, 2014 at 19:46
  • @Milo oh may not be doing that oops May 13, 2014 at 19:46
  • All I need was this query_posts( 'posts_per_page=5' ); been a long time since ive touched wordpress all javascript now thanks May 13, 2014 at 19:49

3 Answers 3


Dont use query_posts or WP_Query if you need it in the main loop. Dont ever use query_posts anyway.

<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

   <?php $current_id = get_the_ID(); ?>
   <?php echo $current_id ?>

            <h1><?php the_field('titleFart', $current_id); ?></h1>

<?php endwhile; // end of the loop. ?>
<?php endif; ?>

Because: get_the_ID()


Please don't use query_posts()

Note: This function isn't meant to be used by plugins or themes. As explained later, there are better, more performant options to alter the main query. query_posts() is overly simplistic and problematic way to modify main query of a page by replacing it with new instance of the query. It is inefficient (re-runs SQL queries) and will outright fail in some circumstances (especially often when dealing with posts pagination). Any modern WP code should use more reliable methods, like making use of pre_get_posts hook, for this purpose.


In your case, you are creating a secondary loop on a page so what you want is a new WP_Query object.

$q = new WP_Query(
    'posts_per_page' => 5

if ( $q->have_posts() ) {
  while ( $q->have_posts() ) {
    $current_id = $post->ID;
    echo $current_id ?>
      <h1><?php the_field('titleFart', $current_id); ?></h1><?php 
  } // end of the loop. 

Use wp_query() with your params instead. Query_posts slows down your queries. http://codex.wordpress.org/Class_Reference/WP_Query

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.