Adding a Short Code Function to Include Any PHP or HTML Files in the WordPress Posts or Pages


Sometimes, we want to include the PHP or HTML or external files in a wordpress post or page, then we can use the following PHP code to add a shortcode function in WordPress:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function include_php_in_wordpress($atts) {
    extract(shortcode_atts(
        array(
            'src' => ''
    ), $atts));
 
    if ($src!= '') {
        if (is_file($src)) {
            return @file_get_contents($src);
        } else {
            return "";
        }
    }
}
 
add_shortcode('include_php_in_wordpress', 'include_php_in_wordpress_func');
function include_php_in_wordpress($atts) {
    extract(shortcode_atts(
        array(
            'src' => ''
    ), $atts));

    if ($src!= '') {
        if (is_file($src)) {
            return @file_get_contents($src);
        } else {
            return "";
        }
    }
}

add_shortcode('include_php_in_wordpress', 'include_php_in_wordpress_func');

You can add it in your theme template (child) functions, so that in your wordpress posts or pages, you can do this:

1
[include_php_in_wordpress src="/path-to-the-php/hello.php"]
[include_php_in_wordpress src="/path-to-the-php/hello.php"]

This is extremely useful, if you want to include some PHP files in some of the wordpress posts, for example, the “Related Posts”, you can hand-pick the posts, save them in an external PHP or HTML file, then include this using the above short code function in all related posts. So you don’t need to update those related posts if you want to insert/remove a post from the “Related Posts” list.

Wordpress is King!

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
286 words
Last Post: Teaching Kids Programming - Minimum Operations to Reduce an Integer to 0 (Greedy Recursion/Top Down Dynamic Programming Algorithm)
Next Post: Teaching Kids Programming - Minimum Operations to Reduce an Integer to 0 (Greedy/Iterative Algorithm)

The Permanent URL is: Adding a Short Code Function to Include Any PHP or HTML Files in the WordPress Posts or Pages

Leave a Reply