Pergunta

I've encountered an issue that I can't seem to figure out.

I am using require_once to place content before and after the page content on my homepage. The before content works perfectly and displays fine. If I use text for the after content such as $aftercontent: 'this is my text';

However, if I attempt another require_once call the after content is situated directly beneath my before content, and before The $content. Code below.

// -----------------------------------------
// HOMEPAGE HERO & FOOTER CALL

function wpdev_before_after($content) {
    if ( is_user_logged_in() && is_front_page() ) {
        $beforecontent = require_once ( WP_CONTENT_DIR . '/themes/moon-child/includes/hero-registered-include.php' );
        $aftercontent = require_once ( WP_CONTENT_DIR . '/themes/moon-child/includes/footer-registered-include.php' );
        $fullcontent = $beforecontent . $content . $aftercontent;
    } else {
        $beforecontent = require_once ( WP_CONTENT_DIR . '/themes/moon-child/includes/hero-unregistered-include.php' );
        $aftercontent = require_once ( WP_CONTENT_DIR . '/themes/moon-child/includes/footer-unregistered-include.php' );
        $fullcontent = $beforecontent . $content . $aftercontent;
    }

    return $fullcontent;
}
add_filter('the_content', 'wpdev_before_after');
Foi útil?

Solução

If the file you want to attach (eg. footer-registered-include.php) print/display some text, this text will be displayed in the time you include the file.

To assign to the variable the content displayed by the included file you should:

  1. turn on output buffering
  2. include file
  3. contents of the output buffer and end output buffering
function wpdev_before_after($content)
{
    if ( is_user_logged_in() && is_front_page() )
    {
        ob_start();
        require_once( get_stylesheet_directory() . '/includes/hero-registered-include.php' );
        $beforecontent = ob_get_contents();
        ob_clean();
        // -- OR --
        // $beforecontent = ob_get_clean();
        // ob_start();

        include_once( get_stylesheet_directory() . '/includes/footer-registered-include.php' );
        $aftercontent = ob_get_clean();

        $fullcontent = $beforecontent . $content . $aftercontent;
    }
    // else {
    // ...
    // }
    return $fullcontent;
}
add_filter('the_content', 'wpdev_before_after');

References:

Licenciado em: CC-BY-SA com atribuição
Não afiliado a wordpress.stackexchange
scroll top