Home > OS >  PHP include via shortcode is moved by WP Gutenberg Editor
PHP include via shortcode is moved by WP Gutenberg Editor

Time:01-26

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?

CodePudding user response:

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.

  • Related