How to use a PHP include with WordPress

Glenn Glenn's Blog 0 Comments

For those of you who are familiar with PHP then you’ll know that using an include is an effective way of adding a file that is easily up-dateable site-wide. A good example would be a navigation, header or footer that is ‘included’ on the page from a source file (usually a .php or .html file). You may however not be aware that a php include for an ‘external file’ can also be added from within WordPress itself and this is extremely useful say if you have an external application that you have created that you need to hang on to.

There are various ways to do this and these are listed below:-

Include an External File within a WordPress Template

The key here is using the term ‘ABSPATH’ or WordPress will throw up errors such as “syntax error, unexpected T_STRING”

<?php include(ABSPATH . ‘/filename.html’); ?> 

and

<?php include(ABSPATH . ‘/mydir/filename.html’); ?> 

equally

<!--?php include(ABSPATH . 'wp-content/data.php'); echo "fail"; ?>

Include an External File with WordPress Plugin

A handy plugin for WordPress php includes is ‘Include HTML and PHP’ and you can download it from the WordPress Plugin Repository from:-

http://wordpress.org/extend/plugins/simple-include/

Limitations

We have found that on current release the plugin will only look for includes within the Theme folder, but luckily there is another way: –

Include PHP with WordPress Plugin

You can also achieve the same efect by using a plugin to run PHP script from within WordPress. There are a few plugins that can do this, but we rather like 5 Sec Run PHP which is a plugin from codecanyon.net.

Implementation

The best method we have found to achieve this is with the following php code that can reference any file from the site root and inject it into WordPress using the plugin above:-



$path = $_SERVER['DOCUMENT_ROOT'];
$path .= "/mydire/filename.html";
include_once($path);

Add the code between your bracketed ‘php’ tags

PHP Include from Root

if you not using WordPress, or are interested, then you can also use any of the following snippets to php include  from Root:-

As per the above


<?php  $path = $_SERVER['DOCUMENT_ROOT']; $path .= "/mydire/filename.html"; include_once($path); ?>

or


<?php  set_include_path( implode( PATH_SEPARATOR, array( $_SERVER['DOCUMENT_ROOT'], get_include_path() ) ) ); include 'mydire/filename.html'; ?>

or simply


<?php  php require_once $_SERVER['DOCUMENT_ROOT'] . ” /test/courses.html ” ; ?>

About the Author
How to use a PHP include with WordPress How to use a PHP include with WordPress 0da77002febbfe28d15144a57bbcc2c9 s 180 d mm r g

Glenn

A highly experienced WordPress Web Developer, Front-end and Back-end Developer & New Media Specialist with extensive knowledge of a wide spectrum of technologies in the Development and Creative Industries built up over a number of years.

Leave a Reply

Your email address will not be published. Required fields are marked *