Home > Net >  wordpress php shortcode output
wordpress php shortcode output

Time:07-26

I am trying to connect a filepath to my wordpress page. The filepath I am trying to connect to should be:

'/wp-content/themes/bb-theme-child/php/Hello.php'

Hello.php is:

echo "Hello World"

Here is my code that i have written:

/* SHORTCODE TO HAVE FILES */
add_shortcode('data1', function($atts) {
    $atts = 'Some post: ' . include dirname(__Hello.php__) . '/wp-content/themes/bb-theme-child/php/Hello.php';
    echo $atts;
});

Whats strange is the output:

echo "Hello!";Some post: 1

Im not sure what Some post: 1 is, nor the reason why Some post comes AFTER Hello.php

CodePudding user response:

The add_shortcode function requires all the output to be returned not echoed

From the docs: https://developer.wordpress.org/reference/functions/add_shortcode/

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.

That being said, your shortcode should look like:

add_shortcode('data1', function($atts) {
    ob_start();

    echo 'Some post: ';

    include dirname(__Hello.php__) . '/wp-content/themes/bb-theme-child/php/Hello.php';

    // do more stuff here maybe ?        

    return ob_get_clean();
});

!!! Also, make sure your Hello.php file has an open PHP tag before the echo "Hello World" line.

NOTE: Not sure what is your expected output, but this is how I interpreted your code.

You may learn more about WordPress shortcodes from the official docs or from this article I wrote

  • Related