bccarlso
bccarlso

Reputation: 187

How do I use conditionals to differentiate between Page and Subpage in WordPress?

I have been using conditionals to be able to tell if I'm on a page or a subpage of that page, but I cannot for the life of me get the code to do one thing if I'm on the master page,and another thing if I'm on a subpage of that master page. This is what I have been using so far:

if ( is_page('3') || $post->post_parent == '3' ){}

Does anyone know how to check for page and subpage? In ExpressionEngine, I would use the URL slugs, but I'm not sure how to do this in WordPress. Thanks in advance!

Upvotes: 0

Views: 409

Answers (1)

Galen
Galen

Reputation: 30170

did you try this from wordpress codex

Testing for sub-Pages

There is no is_subpage() function yet, but you can test this with a little code:

Snippet 1

<?php

 global $post;     // if outside the loop

 if ( is_page() && $post->post_parent )
 {
     // This is a subpage

 } else {
     // This is not a subpage
 }
?>

Using the URL

$url = '/shop/';
$url2 = '/shop/category/accessories';

function isSubPage( $page, $url = null ) {

    if ( strtolower(trim( $url, '/' )) == $page ) {
        return false;
    }
    return true;

}

var_dump(isSubPage( 'shop', $url )); //false
var_dump(isSubPage( 'shop', $url2 )); //true

for the second argument you're goign to want to put $_SERVER['REQUEST_URI'] or whatever variable you can get the request from

var_dump(isSubPage( 'shop', $_SERVER['REQUEST_URI'] ));

Upvotes: 1

Related Questions