Forums

the_ID and $wp_query->post->ID always return the same number (10 posts)

  1. jonathan.clarke
    Member
    Posted 3 years ago #

    For some reason the_ID and $wp_query->post->ID always return the same number for post 283. Despite browsing to other posts, I always get 283.

    Anyone know what might be causing this?

  2. MichaelH
    Volunteer
    Posted 3 years ago #

    The the_ID is meant to be used in The Loop.

  3. jonathan.clarke
    Member
    Posted 3 years ago #

    So the sidebar is in The Loop?

  4. MichaelH
    Volunteer
    Posted 3 years ago #

    Not really.

    $id and $post->ID are two variables that you might consider using but it depends on what you ultimately are trying to achieve.

  5. jonathan.clarke
    Member
    Posted 3 years ago #

    OK, here's what I want to achieve...

    I want to display custom field (meta) data in the sidebar when viewing the single post view. The data should be specific to the post viewed.

    To get the custom field functions to work I need to feed them the current post ID.

    For some reason I'm unable to echo out the current post ID from within the sidebar.

    Here is my sidebar code:

    global $post;
    $side_ID = $post->ID;
    echo '<h4>Post ID</h4>';
    echo 'the_ID: '.the_ID().'';
    echo 'get_the_ID: '.get_the_ID().'';
    echo 'bpl_post_ID: '.$bpl_post_ID.'';
    echo 'side_ID: '.$side_ID;

    Here is my content code:

    global $wp_query;
    $bpl_post_ID = $wp_query->post->ID;
    echo $bpl_post_ID;
    global $bpl_post_ID;

    The content code displays the correct post ID, but the sidebar code doesn't.

  6. MichaelH
    Volunteer
    Posted 3 years ago #

    You need global $bpl_post_ID; in your sidebar.

  7. jonathan.clarke
    Member
    Posted 3 years ago #

    Trying that right now...

  8. jonathan.clarke
    Member
    Posted 3 years ago #

    Nope, didn't work:

    Sidebar

    global $post;
    $side_ID = $post->ID;
    global $bpl_post_ID;
    echo '<h4>Post ID</h4>';
    echo 'the_ID: '.the_ID().'';
    echo 'get_the_ID: '.get_the_ID().'';
    echo 'bpl_post_ID: '.$bpl_post_ID.'';
    echo 'bpl_post_ID2: '.$bpl_post_ID->ID;

    Content

    global $wp_query;
    $bpl_post_ID = $wp_query->post->ID;
    echo $bpl_post_ID;
    global $bpl_post_ID;
  9. MichaelH
    Volunteer
    Posted 3 years ago #

    Used this on the WordPress Defaut Theme's sidebar.php:

    <?php if (is_single()) {
    $custom_fields = get_post_custom(get_query_var('p'));
    $my_custom_field = $custom_fields['my_custom_key'];
    if ($my_custom_field) {
    foreach ( $my_custom_field as $key => $value ) {
      echo $key . " => " . $value . "<br />";
    }
    }
    }
    ?>
  10. jonathan.clarke
    Member
    Posted 3 years ago #

    I'll try that...

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags