How to include a PHP file in a WordPress Site

How To Include A Php File In WordPress Site
How To Include A Php File In WordPress Site

This little “PHP include” guide, will show you how to include a PHP-file in your WordPress theme (using a relative path). This snippet isn’t so much a “WordPress snippet”, but really just the PHP include function, using WordPress get_template_directoryto get the relative path for the file.

Why you need to should choose a relative path and not an absolute/static path

When you want to include a PHP file (or image file, HTML file, etc.), it is required to specify a specific path that instructs the webserver, on where the webserver should locate the specific file. There are multiple ways to go about this, such as:

  • Using a absolute/static path (not recommended) – specifying the location of a file or directory from the root directory(/).
  • Using a relative path (best practice) – the path related to the present working directly(pwd), starting at your current directory and never starts with a “/”.

The WordPress get_template_directory() function

The built-in WordPress function get_template_directory, retrieves the current theme directory by returning an absolute server path (eg: /home/user/public_html/wp-content/themes/your_theme_file), and not a URI.

If you are using a WordPress child theme

If you are using a child theme, the absolute path to the parent theme directory will be returned – and this will not work. If you are using a child theme, then you would have to use the WordPress function: get_stylesheet_directory() instead, to get the absolute path to the child theme directory.

This is how to include a PHP file in a WordPress theme

In this PHP include example, we are going to use a relative path, using the WordPress built-in function: get_template_directory.

[php] include get_template_directory() . ‘/include/yourfile.php’;[/php]

This is how to include a PHP file in a WordPress child theme

In this PHP include example, we are going to use a relative path, using the WordPress built-in function: get_stylesheet_directory().

[php] include get_stylesheet_directory() . ‘/include/yourfile.php’;[/php]

Links To Read More Information About Php Include

Spread the love

You Might Also Like

Leave a Reply

Your email address will not be published.