0

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

2

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you for your help! However, none of the php code actually runs. Instead, it appears that all of my code that is printed out in Hello.php is just printed out in the word document. It should just say Hello! and not echo Hello!
in your Hello.php, do you have a PHP open tag <?php ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.