0

Is it possible to find out what page a post is contained in?

Im in my single.php template and im listing child pages in a sidebar using wp_list_pages, I want the page (not category) that the post is visible in to be highlighted, or add current_page_item to it, is this possible? It works everywhere else at the moment except for the single.php template.

1 Answer 1

0
$ancestors = array();
$ancestors = get_ancestors($post->ID,'page');
$parent = (!empty($ancestors)) ? array_pop($ancestors) : $post->ID;

$parent should be the topmost page parent.

However, if you are using a WordPress generated menu there is a pretty good chance that there is already a item identified by a CSS class as the parent. Take a good look at the generated markup.

http://codex.wordpress.org/Function_Reference/wp_nav_menu#Menu_Item_CSS_Classes

Note: using wp_list_pages, for nested pages, current_page_parent applies to the immediate parent only but current_page_ancestor is applied to all of the parent pages. That is the class you want (I think). Just adjust your CSS.

8
  • That throws back a different page ID than i require! and yes i am using a wp generates menu
    – user34466
    Commented Jun 28, 2013 at 18:48
  • Then your description is not adequate to identify the problem. What post/page ID do you require?
    – s_ha_dum
    Commented Jun 28, 2013 at 18:50
  • Im using wp_list_pages to list child pages in a sidebar. So for example, if im in 'About', it lists the child pages of 'About'. If i click one of them, for example 'About Child' it takes me to that page and it spits out the class current_page_item in the sidebar for the page named 'About Child'. If i then click onto a post inside 'About Child', which takes me into my single.php template, i loose the current_page_item in the sidebar, im trying to retain it
    – user34466
    Commented Jun 28, 2013 at 18:58
  • @user34466 : see the edit
    – s_ha_dum
    Commented Jun 28, 2013 at 19:20
  • thanks i really appreciate your help, just tested, i noticed what its doing now, its giving me the id of the current post, but not the child page i need still
    – user34466
    Commented Jun 28, 2013 at 19:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.