0

I currently have a function that checks to see if the page is a parent, and if so, do stuff. But I also want to check to see if the parent has a child page that has a certain slug.

Basically, how would I check to see if a WordPress page has a child that matches a slug of my-child-slug?

In short, this is my current function:

/* Using Slug, make iconbox Shortcode */
function fs_sc_location_iconbox( $atts ){ 
    // begin output buffering
    ob_start();

    global $post; // if outside the loop

    $response = 'Nothing to see here';

    if ( $post->post_parent ) {
        // This is a subpage
        $slug = $post->post_name;

    } else {
        // This is not a subpage
        $slug = $post->post_name;

        // Check if has child page with slug of my-child-slug
        // ** NEED LOGIC HERE **

        // if this parent page has a child with the desired child slug...
        $response = 'Yes, this parent has a child page that we are looking for.';

    }

    // if there is a slug
    if ($slug) {
        // output the default response, unless this page is a parent of the desired child page
        echo $response;
    }
    // end output buffering, grab the buffer contents, and empty the buffer
    return ob_get_clean();
}
add_shortcode( 'fs_location_iconbox', 'fs_sc_location_iconbox' );

How can I updated te // ** NEED LOGIC HERE ** area, so that it checks if this parent page has a child of the my-child-slug slug? And if so, then it will set a new value for the $response variable.

0

For now I was able to achieve it by adding this to my function:

$slug_to_check = 'my-child-slug';

// go through each child page we found
foreach( $child_pages as $child_page ) {        

    // get the slug of this child page we found
    $child_slug = $child_page->post_name;
  
    // get the link of this child page we found
    $child_link = get_page_link( $child_page->ID );
  
    // if the child page we found has the slug we want
    if($child_slug === $slug_to_check) {
      
        // output the child page link
        $response = 'Yes, this parent has a child page that we are looking for.';
    
    }  
}   

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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