Search code examples
phpwordpressphp-7.0

PHP Function echo included file


I'm currently developing a wordpress plugin. I created a shortcode which displays the content of another html/php file this looks like this:

function df_display_form()
{
    // Fetching some data with $wpdb

    // Display the data
    include_once plugin_dir_path(__FILE__) . 'markup/show-dynamic-form.php';
}

My problem is that the shortcode will be showed at the top of the page. So I googled this issus and found a solution. As it is writte there the problem is that return should be used instead of echo.

So my question is how can I return the renderd content from the included file? (not echo).


Solution

  • Try using an output buffer. https://www.php.net/manual/en/function.ob-get-clean.php

    function df_display_form()
    {
        ob_start(); 
        // Fetching some data with $wpdb
    
        // Display the data
        include_once plugin_dir_path(__FILE__) . 'markup/show-dynamic-form.php';
        $out = ob_get_clean();
        return $out;
    }