Are you looking for a way to check if post is a child or not and returns a value to use in an if-statement? While there’s probably a plugin for this, we have created a quick code snippet that you can use to check if post is a child or not in WordPress.
Instructions:
All you have to do is add this code to your theme’s single.php file or in a site-specific plugin:
<?php function ma_is_child_of($page_id) { global $post; $is_child = false; $parents = get_post_ancestors($post); if ($parents) { foreach ($parents as $one_parent_id) { if ($one_parent_id == $page_id) { $is_child = true; break; } } } return $is_child; }; ?>
Note: If this is your first time adding code snippets in WordPress, then please refer to our guide on how to properly copy / paste code snippets in WordPress, so you don’t accidentally break your site.
If you liked this code snippet, please consider checking out our other articles on the site like: 43 best photography themes for WordPress and how to create stunning WordPress optin forms.
Comments Leave a Reply