I’m trying to show different images depending on which section of my site visitors are browsing. My main problem is figuring out how to detect when someone is viewing a page that falls under a specific parent page, even if it’s nested several levels down.
For example, let’s say I have this structure:
Main → Services → Photography
I want to display a special banner whenever someone visits the Services page or the Photography page or any other pages that might be created under Photography later on. If they’re anywhere else on the site, I want to show a different default image.
Is there a reliable way to check if the current page belongs to a particular parent page hierarchy in WordPress?
Been there! Managing a huge corporate site with nested pages everywhere.
PHP works but it’s static and becomes a nightmare with dynamic content. What about A/B testing banners? Changing display logic based on user behavior? Integrating external APIs for personalization?
I automated this with Latenode. Set up a webhook that fires when someone hits any page. The automation checks page hierarchy through WordPress API calls, then serves the right banner based on your rules.
Best part? You can tweak the logic without touching code. Different images for mobile? Add a condition. Pull banners from a CDS by user location? Hook it up. Track performance? Auto-log everything.
Mine even auto-generates and optimizes banner variations with AI when new pages get created under specific parents. Takes 10 minutes to build the initial flow.
try using wp_get_post_parent_id() in a loop. just climb up the hierarchy till you hit your target parent or reach the top. it’s cleaner and avoids caching issues compared to the ancestor approach.
I’ve hit this same issue on a client site with crazy deep page structures. Here’s what works: combine $post->post_parent with a recursive function that climbs the tree until it finds your target parent or hits zero. Game changer for me was caching the result in a transient for 24 hours - saves you from hammering the database on every page load, especially on bigger sites. Watch out though - flush those transients when you move pages around or restructure things. Otherwise you’ll get stale data and banners popping up where they shouldn’t. Don’t forget to test in preview mode since drafts can act weird with hierarchy checks.
Had the same issue on a multi-section site. Use get_post_ancestors() with the current page ID - works great. I wrote a function that grabs all ancestor IDs for the active page and checks if your target parent ID is in there. Handles any level of nesting. You could also use is_page() with an array of IDs, but the ancestor method is way more flexible when you add new pages later. Don’t forget to cache that parent ID or you’ll take a performance hit.