Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP include via shortcode is moved by WP Gutenberg Editor

I’d like to include a specific php-file into a WP post. Therefore, I’m using the default WP Gutenberg editor. In the middle of the post, I inserted a shortcode like [my-php-file]. In my functions.php I used the following code:

function include_file ( $atts ) {
   include('file.php');
}
add_shortcode( 'my-php-file', 'include_file')

So far, so good. The content of my php-file is loaded, but on the top of the WP post and not in the middle, where the shortcode is placed.

Can anybody tell me please why this is happening and how I can fix this issue? So that the php-file will be displayed and included in the middle of the post?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The add_shortcode callback expects you to return content, by including the file it will execute the code and output the content to the output buffer (rather than as the function result).

You can try using output buffering to return content rather than outputting it straight into display, as in:

function include_file ( $atts ) {
   ob_start();
   include('file.php');
   return ob_get_clean();
}
add_shortcode( 'my-php-file', 'include_file')`

You can find more information on the WordPress Documentation at https://developer.wordpress.org/reference/functions/add_shortcode/#more-information :

Note that the function called by the shortcode should never produce an
output of any kind. Shortcode functions should return the text that is
to be used to replace the shortcode. Producing the output directly
will lead to unexpected results. This is similar to the way filter
functions should behave, in that they should not produce unexpected
side effects from the call since you cannot control when and where
they are called from.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading