WordPress.org

Ready to get started?Download WordPress

Forums

Getting actual page ID after calling the loop (5 posts)

  1. iron77
    Member
    Posted 6 years ago #

    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

  2. Samuel Wood (Otto)
    Tech Ninja
    Posted 6 years ago #

    $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.

  3. iron77
    Member
    Posted 6 years ago #

    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?

  4. iron77
    Member
    Posted 6 years ago #

    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?

  5. Samuel Wood (Otto)
    Tech Ninja
    Posted 6 years ago #

    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.

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags