0
votes

I'm trying to create a basic short code in Wordpress that will allow me to run PHP on pages. This is what I have so far, but it isn't working. Advice?

The idea is it will be [php] Insert PHP here [/php']

<?php
function php_shortcode( $attr, $content = null ) {
    return '<?php' . $content . '?>';
}
add_shortcode('php', 'php_shortcode');
?>

Thank you.

3
Are you trying to execute that code? If so that doesn't really jive with shortcodes. - Seth Battin
You'd have to eval($content) but you might be opening yourself up for exploitation. - mpen
Are you fully aware of the security issues with what you are trying to do? I have essentially tried the ideas of mpen and @digout. Although correct in principle there are significant problems because of the way WordPress does 'the_content' filters. I think I have the workaround but I will not proceed unless you are still interested after considering the security issues. - user8717003

3 Answers

1
votes

Sorry to say you are exploring a concept that simply cannot yield success. The PHP that renders the shortcode, cannot "also" render code within itself.

0
votes

Short codes as standard will filter PHP tags. You can however write php directly into the content editor. Without giving you all the advisories why it's not recommended, you can do something like the following which will allow you to write php into the content editor:

// write '<?php ... ?>' into the editor 

add_filter('the_content', 'allow_php', 9);

function allow_php($content) {
    if (strpos($content, '<' . '?') !== false) {
        ob_start();
        eval('?' . '>' . $content);
        $content = ob_get_clean();
    }
    return $content;
}
0
votes

After thinking about this for a little while I realized there is an obvious solution. So, someone probably has written a plugin to do it and someone has - https://wordpress.org/plugins/inline-php/.

It consists of about 40 lines of PHP. The critical implementation trick is it is not done as a shortcode but as a 'the_content' filter.

add_filter('the_content', 'inline_php', 0);

This is done before other 'the_content' filter processing and avoids all the problems that I encountered trying to use it as a shortcode. Of course, there is still a significant security risk.