Conditional statement to check for page.php usage on WordPress

Is there a way to check to see if the page.php template is being used? The standard way isn’t working:

 <?php echo is_page_template("page.php") ? "Page being used" : "Page not being used"; ?>

However if I change page.php to any other template (page-about.php etc) it works fine.

Related posts

2 comments

  1. Actually it is very simple
    Just use:

    is_page_template()

    If it returns true than page.php is not being used and vice versa
    🙂

  2. I could not get is_page_template(); to work properly either. I put this into footer.php and header.php to test it and it shows me which page template is being used as well as whether page.php is being used. If it is put in the header it could easily be adapted to control what happens next on the page.

    It should probably be done properly WordPress style and put into your functions.php in your child theme but this is the basic code:

     <?php  $temp = explode('/', get_page_template()); 
            if( $temp[count($temp)-1] == "page.php" ) {
              echo " page.php is being used.";
            }else{
              echo  $temp[count($temp)-1] . " is being used.";
            }
     ?>
    

    It gets the full path of the current template, splits off the page name and compares or echoes it. If you are actually going to echo it and not just use its functionality to modify other display parameters then you should enclose it in htmlspecialchars(); to avoid inject attack.

     <?php  $temp = explode('/', get_page_template()); 
            if( $temp[count($temp)-1] == "page.php" ) {
              echo " page.php is being used.";
            }else{
              echo  htmlspecialchars($temp[count($temp)-1]) . " is being used.";
            }
     ?>
    

    This looks like a discussion of a more WordPressy way to do it and a possible reason why it was not working – though I would have thought that by the time you get to footer.php it should be pretty clear which template was used https://wordpress.org/support/topic/is_page_template-in-functionsphp-not-working

    Just for reference this is the WordPress method with comments on its limitations when used inside The Loop. https://developer.wordpress.org/reference/functions/is_page_template/

Comments are closed.