I need to include external php file only on homepage of my website.
But, since all the pages on the site use the same page template (homepage template), I cant filter them based on that so I was wondering is there a way to include PHP file ONLY on homepage URL (which is www.domain.com/folder) and not to show it on any other page (for example www.domain.com/folder/lorem).
I tried using this snippet in my header.php file:
<?php
if ($_SERVER['PHP_SELF'] = '/')
include('some-file.php');
?>
and the file gets included on all other pages as well.
I am a PHP newbie so sorry if it is stupid question :)
UPDATE: I did changed it to
<?php
if ($_SERVER['PHP_SELF'] == '/')
include('some-file.php');
?>
and it still isnt showing up.
You can use WordPress's is_front_page()
function to check.
Thus, your code should be:
<?php
// if code does not work, adding the next line should make it work
<?php wp_reset_query(); ?>
if ( is_front_page() ) {
include('some-file.php');
}
?>
Source: https://codex.wordpress.org/Function_Reference/is_front_page
Alternatively, if the above is not working, you can try:
if ( $_SERVER["REQUEST_URI"] == '/' ) {
include('some-file.php');
}
As a last resort, try using plugins to insert PHP directly into the pages, one such plugin is https://wordpress.org/plugins/insert-php/.
UPDATE: After the elaboration in comments, I've come up with an alternate method, as shown below.
In your case, this might work. This code would get the URL first, then parse it to get the directory, and assign the directory to $directory
. If it is a on the homepage, the $directory
will not be set, thus include some-file.php
.
<?php
// Get URL
$link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
// Get Directory (eg. will return 'folder' in example.com/folder/files)
$parts = explode('/', $link);
$directory = $parts[3];
// If $directory is null, include PHP (eg. example.com, there is no directory)
if ($directory == ''){
include('some-file.php');
}
?>
Hope the above methods help, thanks!