0

I'm currently working on a plugin. I have to render a lot of html on a specific page. I've placed that piece of code in the plugin it's core file, like so:

    add_filter('the_content', 'overwrite_content');
 
function overwrite_content($content) {
    if(is_page('Signup')){
        require_once(plugin_dir_path(__FILE__).'/views/signup.php');
        $content = '';
    }
    else if(is_page('Bedankt')){
        require_once(plugin_dir_path(__FILE__).'/views/thanks.php');
        $content = '';
    }
    return $content;
}

It all works fine, but for some reason all <head> elements are being placed underneath my custom html within the <body> think of <meta, <title> etc.

Does anyone know how I fix this? I'd rather skip creating a shortcode, since the html is just simply too much.

6
  • 2
    you can't insert HTML into the <head> tag from inside a shortcode or from the_content filter, and you shouldn't be outputting HTML directly to the browser inside that filter, you need to return it instead. Otherwise that output happens immediatley, not at the location the filtered HTML is used
    – Tom J Nowell
    Jun 23, 2022 at 13:43
  • I know I can't insert HTML into the <head> . But in what way returning do you mean? Like return '<div>test</div>';?
    – Jorn Reed
    Jun 23, 2022 at 14:20
  • yes, by calling require_once you're outputting directly to the browser any templates/tags the same way print or echo does. That way the output of those files is immediately sent when they're executed
    – Tom J Nowell
    Jun 23, 2022 at 15:51
  • Ah okay, than I know return will do the trick. But what if my HTML has like atleast 200 lines. Doesn't it become too big of a return?
    – Jorn Reed
    Jun 24, 2022 at 7:15
  • that's a PHP problem, with lots of other solutions unrelated to WordPress, e.g. output buffers, Eitherway PHP won't change how it works to make 200+ lines more convenient. Keep in mind too that the solution you chose to put your code into the template of filtering the content and title is not the only method available. The general gist I was trying to say though, is if you want to add meta/title tags etc to the page, the content filter or a shortcode are far too late, it needs to happen much earlier while WP outputs the header
    – Tom J Nowell
    Jun 24, 2022 at 10:12

0

Your Answer

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

Browse other questions tagged or ask your own question.