WordPress is_child_of: Is this a child of page x?


/ Published in: PHP
Save to your folder(s)

This makes template code that applies to children of a particular page much more readable, especially if you can use a page path instead of an ID: `if ( is_child_of( 'topic/subtopic' ) ) :`.


Copy this code and paste it in your HTML
  1. function is_child_of( $page_id, $potential_child_id = '' ) {
  2.  
  3. $is_child = false;
  4.  
  5. if ( ! is_int( $page_id ) ) {
  6. $page = get_page_by_path( $page_id );
  7. $page_id = empty( $page ) ? 0 : $page->ID;
  8. }
  9.  
  10. if ( empty( $potential_child_id ) ) {
  11. $potential_child_id = get_the_ID();
  12. }
  13.  
  14. $potential_child = get_page( $potential_child_id );
  15.  
  16. if ( ! empty( $potential_child ) && is_array( $potential_child->ancestors ) ) {
  17. $is_child = in_array( $page_id, $potential_child->ancestors );
  18. }
  19.  
  20. return $is_child;
  21. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.