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.
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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.';
}
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0