Search code examples
javascriptphphtmlheader

How to let script only show in homepage?


I need to include script code schema only on homepage of my website.

But, I do not know too much about PHP code, I cant filter them based on that so I was wondering is there a way to include script code schema ONLY on homepage URL and not to show it on any other page.

I tried using this :

<?php if( is_front_page() ): ?>
  <script type="application/ld+json">
  { 
    "@context": "https://schema.org",
    "@type": ...
    ...
  }
  </script>
<?php endif; ?>

Any suggestions are appreciated!

Thanks so much!


Solution

  • Use $_SERVER['REQUEST_URI']. Dump it on your homepage to figure out what your homepage url is, for example for me the url is: http://localhost:3000/index.php so my $_SERVER['REQUEST_URI'] for that page will be /index.php. For you depending on the config it can be just / or any other value. Note that value and use that in your if check:

    <?php
    
    var_dump($_SERVER['REQUEST_URI']);
    
    if($_SERVER['REQUEST_URI'] === '/index.php') {
      echo 'its homepage';
    }
    

    Output on index.php:

    string(10) "/index.php" its homepage
    

    Output on other.php:

    string(10) "/other.php"