Forums

The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Other Get the ID of the current page (WordPress)

  • This topic is empty.
Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #31935
    gno
    Member

    Hi guys,

    On the current project I’m working on, I’m attempting to create a sort of dynamic menu. The page consist of 5 toplevel pages, which is to be shown on all those pages – all of them, but the active one. So if we say we are on page 5, it should show page 1 to 4.

    On the frontpage i achieved this by some wp_list_pages hacking. Something like ‘sort_order=asc&offset=2&number=4’. That was possible as the frontpage has its own template file, and it is ranked as the lowest one.

    However, I’d like to do one template file for the rest of the pages and I was thinking of something like this:

    How do I get the ID of the current page?

    The function the_ID() is only for use within a loop.

    I know that the ID is passed to the body_class() function – I guess I could do some PHP hacking and extract it from there. There must be a smarter way!

    I could just hide the active page by getting all 5 from wp_list_pages and setting display: none; on the current page link – but I’d rather find another solution.

    I hope some of you have experience with this kind of issue, or are better at googling or looking in references than I am ;-)

    #56105
    gno
    Member

    I got around it with a small hack.

    What I did was to use two loops on the same page. First one extracting the title (a the_title() with three arguments, two empty strings and a false boolean, to avoid it echoing) and using get_page_by_title() to extract the ID. By putting that in a variable, I was able to do a wp_list_pages(‘exlude=’.$variable->ID); and achieving what I wanted to. And then running the second loop to output the content.

    I’m still convinced that there’s another way to achieve this – so please let me know if you are familiar with one.

    #95603
    peterrknight
    Member

    For people with the same issue of grabbing the post ID I wrote a better solution on my website: Access the current page id anywhere

    Basically it involves storing the id in a global variable which you can then access anywhere you need. The global is set with a hook to wp_head by accessing the main page query. Read more on my website for the function.

    The above use case would then look like this:


    global $main_post_id;
    wp_list_pages('sort_order=asc&number=4&exlude='.$main_post_id.');
    ?>
Viewing 3 posts - 1 through 3 (of 3 total)
  • The forum ‘Other’ is closed to new topics and replies.