Custom plugin template rendering after </html>. Overriding template duplicates <html> block in page

Turns out that the problem was this snippet I was using to make my theme compatible with BuddyPress.

Does someone know why it was creating the conflict? (would be useful to undersand it and to have it documented somewhere)


/**
 * Adds BuddyPress compatibility
 */
add_filter('bp_template_include_theme_compat', function ($template) {

    if (strpos($template, "mec-events") !== false) {
        return $template;
    }

// Find any oif the templates mentioned by BP codex
    $theme_template = locate_template([
        'plugin-buddypress',
        'buddypress',
        'community',
        'generic',
        'page',
        'single',
        'singular',
        'index',
    ]);
    // Load template from theme if it exists
    if ($theme_template) {
        $data = collect(get_body_class())->reduce(function ($data, $class) {
            return apply_filters("sage/template/{$class}/data", $data);
        }, []);

        echo template($theme_template, $data);
        return get_stylesheet_directory() . '/index.php';
    }

    return $template;

}, PHP_INT_MAX, 1);

/**
 * Prepares BuddyPress classes for usage with Controller
 */
add_filter('body_class', function (array $classes) {
    if (function_exists('bp_get_the_body_class')) {
        $bp_classes = array_filter(bp_get_the_body_class());

        if (!empty($bp_classes) && is_array($bp_classes)) {
            foreach ($bp_classes as $bp_class) {
                // We need to append 'bp-' to classes like 'directory'.
                // It will help to sort the Controller Classes and avoids duplicated classes:
                // e.g. class BpDirectory for 'bp-directory-data'
                $prepend = preg_match('/bp|buddypress/i', $bp_class) ? '' : 'bp-';
                $classes[] = $prepend . $bp_class . '-data';
            }
        }
    }

    return $classes;
}, 100);

/**
 * Adds the resources/views folder as potential
 * parent of buddypress/community folder
 */
add_filter('bp_get_template_locations', function ($locations) {
    return array_merge(
        $locations,
        [
            'views/buddypress',
            'views/community',
        ]
    );
});

FYI, to fix the conflict between this snippet and MEC templates I just inserted this condition at the beginning of bp_template_include_theme_compat's filter:


/**
 * Adds BuddyPress compatibility
 */
add_filter('bp_template_include_theme_compat', function ($template) {

    if (strpos($template, "mec-events") !== false) {
        return $template;
    }
    [...]