how to use conditional tags in wordpress

In this tutorial we are going to show you, how to use conditional tags in wordpress. We given code sample for wordpress theme. How to check page is subpage or parent page.

We got this particular requirement of wordpress menus. For that we need many times parent page menu and sub pages as submenu.

how to use conditional tags in wordpress

Using following code we can able to find the parent page and sub pages from wordpress themes. Following code we can put any where in page or code. We can put this code in header.php or index.php or footer.php or anywhere, as per our requirement.

01<?php
02 
03global $post;&nbsp;&nbsp;&nbsp;&nbsp; // if outside the loop
04 
05if ( is_page() && $post->post_parent ) {
06 
07// This is a subpage
08 
09} else {
10 
11// This is not a subpage
12 
13}
14 
15?>

If you want use or add the is_subpage() method then you need to add the following code in functions.php file.

01<?php
02 
03function is_subpage() {
04 
05global $post;&nbsp;// load details about this page
06 
07if ( is_page() && $post->post_parent ) {&nbsp; // test to see if the page has a parent
08 
09$parentID = $post->post_parent;&nbsp;// the ID of the parent is this
10 
11return $parentID;&nbsp;// return the ID
12 
13} else {&nbsp;// there is no parent so...
14 
15return false; // ...the answer to the question is false
16 
17};
18 
19};
20 
21?>

Published by

Purab

I am Purab from India, Software development is my profession and teaching is my passion. Programmers blog dedicated to the JAVA, Python, PHP, DevOps and Opensource Frameworks. Purab's Github Repo Youtube Chanel Video Tutorials Connect to on LinkedIn

One thought on “how to use conditional tags in wordpress”

Leave a Reply to John Cancel reply

Your email address will not be published.