WordPress.org

Support

Support » Your WordPress » Getting actual page ID after calling the loop

Getting actual page ID after calling the loop

  • Hi
    I’ll try to explain my problem a bit.
    I’m trying to get ID of the present post/page at WordPress. Normally I was doing it by sth like this:

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

    ..but now I want to do it after calling the loop (for showing sth like 3 posts form category X in the page content). Unfortunately it results by getting ID of the last post shown at the loop. Do anyone know any method how to do this?

    Thanks

Viewing 4 replies - 1 through 4 (of 4 total)
  • $id is one of WordPress’s globals. Don’t use it.

    global $post;
    $this-page-id = $post->ID;

    Later, after other Loops, $this-page-id will still be set. In fact, you could just do this:
    $save-this-id = $id;

    $id is already set for you elsewhere.

    Thx for the reply. This one looks live an obv idea, unfortunately it don’t resolves the problem :/. The issue is, that the loop is called at sidebar widget. So I need to create this ‘$this-page-id’ variable somewhere earlier. Then if I make it in the one file i.e. header.php and want to call in the other i.e. footer.php, it seems WordPress don’t see it at footer.php. I tried sth like ‘global $this-page-id’ at footer.php but still with no results. Have any idea how to resolve it?

    Alright, I’ve already found one solution for this problem. I made sth like this in the plugin area:

    function nbm_global_page_id()
    {
      static $runBefore, $thisID;
      if (!$runBefore)
      {
        $runBefore = true;
        global $post;
        $thisID = $post->ID;
      }
      else
        return $thisID;
    }
    
    add_action('wp_head','nbm_global_page_id');

    as u see it puts page ID to the static variable inside the function when its called the first time (at wp_head) and at all next calls it returns stored there page ID. Please give me your thoughts, what u think about this solution?

    I tried sth like ‘global $this-page-id’ at footer.php but still with no results.

    Add global $this-page-id; before you use $this-page-id in the header.php as well. Then you’ll be using the same global in both places.

    Please give me your thoughts, what u think about this solution?

    It’s way overkill. Just get the number you want, stick it in a global variable, and use it wherever you need it.

Viewing 4 replies - 1 through 4 (of 4 total)
  • The topic ‘Getting actual page ID after calling the loop’ is closed to new replies.
Skip to toolbar