5

my shortcode output won't appear where I put it, but rather at the top of the content (top of the post/page content).

And here is my code

function service_shortcode_index() {
global $content;
$output = include ( TEMPLATEPATH . '/service.php' );
return $output;
}

add_shortcode('service_mid', 'service_shortcode_index');

there are some regular HTML lists with widget in "service.php"

The content displays correctly, just in the wrong position.

0

2 Answers 2

13

I think your problem is with the $output = include .... statement. include() returns true or false based whether it was successful - not the content of the file being included. Use output buffering to get the content.

function service_shortcode_index() {
    global $content;
    ob_start();
    include ( TEMPLATEPATH . '/service.php' );
    $output = ob_get_clean();
    return $output;
}

add_shortcode('service_mid', 'service_shortcode_index');
2
  • 1
    the exception to this is if the included file returns its output, for example if service.php contained just return 'something';, 'something' would get assigned to $output rather than true/false.
    – Milo
    Commented Oct 10, 2012 at 16:22
  • You can also directly write return ob_get_clean(); Commented Jun 28, 2022 at 20:40
0

The problem is that the PHP function include (roughly speaking) echoes the content and then returns a boolean value.

If you switch the include for file_get_contents then your $output will be a string of the file content rather than the boolean value indicating the success of the inclusion.

Works for me with Wordpress5.2 & PHP7.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.