If Page Is Parent or Child


SUBMITTED BY: phpsnippets

DATE: Oct. 22, 2015, 3:29 p.m.

FORMAT: Text only

SIZE: 951 Bytes

HITS: 1215

  1. There are built in conditional WordPress functions for testing for a page:
  2. if ( is_page(2) ) {
  3. // stuff
  4. }
  5. Or for testing if a page is a child of a certain page:
  6. if ( $post->post_parent == '2' ) {
  7. // stuff
  8. }
  9. But there is no built in function that combines these two things, which is a fairly common need. For example, loading a special CSS page for a whole "branch" of content. Like a "videos" page and all its children individual videos pages.
  10. This function (add to functions.php file) creates new logical function to be used in this way:
  11. function is_tree($pid) { // $pid = The ID of the page we're looking for pages underneath
  12. global $post; // load details about this page
  13. if(is_page()&&($post->post_parent==$pid||is_page($pid)))
  14. return true; // we're at the page or at a sub page
  15. else
  16. return false; // we're elsewhere
  17. };
  18. Usage
  19. if (is_tree(2)) {
  20. // stuff
  21. }

comments powered by Disqus