How to Add a ShortCode to Include a PHP File in WordPress?


In WordPress, you can add a short code that allows you to include a PHP File at your post.

First, add the following function in your child theme’s functions.php template:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function sc_include($atts, $inc) {
  return get_include_contents($inc);
}
 
function get_include_contents($filename) {
  ob_start();
  // you can change the directory
  $filename = get_theme_root().'/'.get_template().'/'.trim($filename);
  if (is_file($filename)) {        
     @include($filename);
   }
   return ob_get_clean();
}
 
add_shortcode('include', 'sc_include');
function sc_include($atts, $inc) {
  return get_include_contents($inc);
}

function get_include_contents($filename) {
  ob_start();
  // you can change the directory
  $filename = get_theme_root().'/'.get_template().'/'.trim($filename);
  if (is_file($filename)) {        
     @include($filename);
   }
   return ob_get_clean();
}

add_shortcode('include', 'sc_include');

And you can now in your WordPress post, add a short code like this:

This allows the file.php to be included in the wordpress current post/page and be dynamically interpreted by PHP.

Wordpress is King!

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
218 words
Last Post: Teaching Kids Programming - Two Pointer Algorithm to Solve Four Sum Problem
Next Post: BASH Script to Compute the Average Ping to a Domain

The Permanent URL is: How to Add a ShortCode to Include a PHP File in WordPress?

Leave a Reply