How do I make it easy to insert PHP code or an entire PHP file into a WordPress page, post or widget? Make a shortcode!

This is one of my all-time useful and favorite WordPress shortcodes ever.  It’s so simple, just put the code below into your active theme’s function.php file and now you have a very flexible and powerful shortcode where you can embed external PHP — provided the PHP code is in a file on your own site, of course!

function insert_script($atts){

extract(shortcode_atts(array("path" => '',"vals"=>''), $atts));
	return ob_get_clean();

add_shortcode('insert_script', 'insert_script');

Here’s an example of its use.  If you aren’t familiar with PHP’s parsestr() function, please click here.  It’s a handy way to take any regular query string of variables you’d find in a URL, like ?s=1&action=go and “parse” them out into variable/value matches like:  $s=1, $action=”go”, and so on….

This way, you pass useful variables in a verbose way  in your code — it’s pretty transparent so if the code you’re including isn’t cryptic and is easy to follow, then so will the use of this shortcode in your WordPress pages and posts!

Just put this shortcode in any of your pages or posts, or widgets if you’ve managed to turn on shortcodes in your widgets.  If not, click here to see how easy that is.

[insert_script path='/includes/db/database-connection.php' vars="cmd=show_table"]
//Will find the script at the web root includes folder, parse the variables in the query string "vars" with the PHP command "parsestr()" and execute the PHP

About Author:

Senior Cloud Software Engineer and 25+ years experienced video production, video editing and 3D animation services for a variety of global clients including local video production here in Jacksonville, Florida.

Leave a Comment

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