WordPress.org

Forums

how can I put the contents of get_header() in a variable? (7 posts)

  1. kkhan00
    Member
    Posted 4 years ago #

    Okay, I'm about to pull my hair out.

    I need to display wordpress content on a completely separate script which uses the smartyphp templating style that is very daunting to go through because I have never used it before.

    Basically, I know that get_header(); displays the contents of the head.php file. What I want is to actually store all the information displayed from get_header(); into a variable and then just display the variable instead.

    However, the code $content = get_header(); won't cut it because a call to get_header(); actually shows the contents rather than storing it in the variable (or perhaps both? I have to double-check)

    Is there a way to not let it do that? I don't want it to display the contents.

    Any help is appreciated!

  2. kkhan00
    Member
    Posted 4 years ago #

    Can you elaborate a little? I tried this but all it did was again just display the contents of get_header();

    ob_start();
    get_header();
    
      $wordpress_header = ob_get_contents();
    
    ob_end_flush();
  3. have you checked the content of $wordpress_header?

    for instance with: echo $wordpress_header;

    does it contain the header output?

  4. kkhan00
    Member
    Posted 4 years ago #

    no it doesn't.

    The code above doesn't even create a separate output stream I think. By calling get_header(); after ob_start();, it just displays the content on the page as if you were to call get_header(); normally.

    Maybe I'm doing this wrong?

  5. kkhan00
    Member
    Posted 4 years ago #

    sorry, I may have spoken too soon.

    The code I tried above actually does copy the get_header(); content onto the variable, however, it shows the content twice on the page when I try to get the variable content displayed.

  6. kkhan00
    Member
    Posted 4 years ago #

    Okay, I JUST figured this out! woohoo!

    So the reason why it was outputting the header twice is because I was using ob_end_flush which actually outputs whatever was inside the buffer. Changing that to ob_end_clean will get rid of the contents inside the buffer without outputting it to the screen.

    Anyhow, I guess this can be useful to someone in the future. Also, if anyone else knows a better way of doing this PLEASE share it!

    So, in the end, to get the contents of get_header() or any other void functions within WordPress without having it displayed on the screen, use the following code:

    ob_start(); // starts the internal buffer
    get_header(); // or get_footer, etc
    
       $content = get_ob_contents(); //
    
    ob_end_clean();

Topic Closed

This topic has been closed to new replies.

About this Topic