Working on my first WordPress site so I’m sure this is a really basic question. I’m struggling to write a conditional php statement that performs a certain action when a page is a child of a parent page.
For example, rather than just specifying one page, as below, I’d like to specify all pages that have the ‘About Us’ page as a parent:
<?php if (is_page('About Us')) echo 'Hello World!'; ?>
I’ve tried the “child_of” function but it wasn’t as straightforward as I’d hoped.
When I use the below, I get a syntax error – probably just me not knowing how to use the function:
<?php if (child_of('About Us')) echo 'Hello World!'; ?>
Any suggestions?
Add the following function to your functions.php theme file:
Then you can use the following:
Reference: http://codex.wordpress.org/Conditional_Tags
You’re getting an error because there is no such thing as a
child_of()
function in WordPress.child_of()
is a way of searching using the get_pages() function.where ## is the numeric ID (not the name) of the ‘About us’ page.
Simple solution where you want to link to the parent page from the child page; $post->post_parent holds the ID of a page’s parent if there is one or it is zero if there is not one:
so for this case you would want to change the if() to check if $post->post_parent == $id_of_about_page.
This is the final code that worked for me – not sure if it’s the proper way to do what I’m trying to do, but will post for the benefit of anyone with my same question.
I have a set of right hand columns, each specific to a section of the site (each parent page representing a section of the site).
I want the parent page and all of that parent’s child pages to pull the same specific right hand column.
Here’s what I did:
Where the ## represents the ID # of the page.
This code solved the problem for me guys, incase any one is wondering for a alernative:
“9” is the id of the parent page.