Skip to content
Advertisement

Wrapping PHP and HTML in PHP function to create a shortcode

I’m trying to create a shortcode for use in WordPress, that will allow me to use PHP and HTML functionality.

I have created the shortcode and it works using simple echo Hello World, but when I try to use it to display the results of 160 lines of PHP and HTML it simply shows nothing, not even errors.

After trying several different ways, the most simple way seemed to be:

function imported_table( $atts ) {
    $var = file_get_contents(TEMPLATE_DIR . "/imported_table.php");
}
add_shortcode( 'imported_output', 'imported_table');

…where the imported_table.phpcontains my 160 lines of HTML and PHP. The TEMPLATE_DIR is set in wp-config and works as it should – I get no ‘missing file’ erros, at least (after a couple of missteps).

The imported_table.php file is a little lengthy to post here but essentially it’s like this:

<Some HTML>
<?php 
?>
<Some HTML with <?php >>
<?php 
?>
<closing HTML>

It’s a lot of HTML and nested PHP. The code does work by itself if I use it in a PHP plugin for WordPress, but the plugin has been shown to have vulnerbilities, and its own bugs, which is why I’m trying to use this code in a shortcode.

Advertisement

Answer

Can you try this?

Don’t use TEMPLATE_DIR and file_get_contents.

    function imported_table( $atts ) {
        ob_start();
        include(get_template_directory() . "/imported_table.php");
        $var = ob_get_contents();
        ob_end_clean();
        echo $var;
    }
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement