skip to Main Content

I’m creating a website with multiple pages, each one has a different background but the tag is inside header.php to simplify my code.
I wanted to assign a class to the tag (example ) in order to change the background of each page in css.

I tried assigning the class using php with an if because on index.php the header goes without a class (In order to simplify my css so i just have to change the background and not all the other stuff). I’m using the latest version of XAMPP and PHPStorm with PHP 7.3

In the actual file the code would say <?php include "header.php"; ?>
the filename i want is the name of the actual file where header.php is being included.

The code i tried but didn’t work was

<header class="
    <?php if(basename(__FILE__, '.php') == 'index') 
        {
            echo ' ';
        } 
        else {
            echo basename(__FILE__, '.php');
        } 
    ?>">

The results i’m hoping for is that if the header is being used in example.php the class goes like class=”example”.
Right now the class is class=”header” and i want it to be named after the page where header.php is included

2

Answers


  1. Don’t use .php extension just use URL base Name of each page.
    OR

    you can make it using add check on page name like your page is index just

    <div class="<?php $pagename == index ? 'classname' : 'nothing or you can define some class here as well or leave it blank'>"
    

    Thanks

    Login or Signup to reply.
  2. Assign __FILE__ to a variable first (not in header.php) and change your test to use that variable.

    a.php:

    $pagename = basename(__FILE__, '.php'); // 'a'
    

    header.php:

    if ( $pagename == 'a' )
    

    That said, you might not want to use your PHP file structure to decide on the layout, but try something like this instead: https://css-tricks.com/id-your-body-for-greater-css-control-and-specificity/

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search