Get ID of child from child slug, while knowing parent ID

I have a hierarchy that I need to get data from. It’s the child (by slug name) that I need to get while already having knowledge of the parents.

Highest Known Parent Page (slug : 'parent')
|_ Child 1 (slug : 'child-1')
   |_ Page 1 (slug : 'page-1')
   |_ Page 2 (slug : 'page-2')
|_ Child 2 (slug : 'child-2')
   |_ Page 1 (slug : 'page-1')
   |_ Page 2 (slug : 'page-2')
|_ Child 3 (slug : 'child-3')
   |_ Page 1 (slug : 'page-1')
   |_ Page 2 (slug : 'page-2')

Ideally I’m trying to have a result that returns “page-2” consistently, and I am already working within a loop where I know “child-1”, “child-2”, “child-3”, etc.I am just not sure how to query the third level. Any ideas?

I’m probably over-thinking this, as there’s probably an easy way to get an ID of a page from a slug, when you already know the parent. Of course, I’ll need to script contingencies in case “page-2” doesn’t exist for some reason, but I first need to get the right data.

UPDATE:

Here’s the code I’m working with right now. I know models. I know children of models. I’m trying to get each and every one of a certain child underneath all model children. For example, a “specifications” page. So I’m hoping to have like 5-6 different “specifications” pages returned to me…so I can easily link to them (dynamically).

<?php
// get models id
$models = get_page_by_path( 'models' );

// get children of models page
$args = array(
    'post_type'      => 'page',
    'posts_per_page' => -1,
    'post_parent'    => $models->ID,
    'order'          => 'ASC',
    'orderby'        => 'menu_order'
);
$children_posts = new WP_Query( $args );
?>

4 Answers
4

You should use the pagename parameter for WP_Query along with post_parent. Limit your query to one post using posts_per_page.

$parent_id = get_the_ID();
$args = array(
    'post_type'      => 'page'
    'pagename'       => 'page-2',
    'post_parent'    => $parent_id,
    'posts_per_page' => 1
);
$posts = get_posts( $args );
$child = isset( $posts[0] ) ? $posts[0] : false;
if( $child ){
    //Do Something
}

This, in theory, should render your desired post by slug using the parent ID.

Leave a Comment