• Resolved UlukaiThemeDesign

    (@ulukaithemedesign)


    I want to strip out all the whitespace before php/wordpress outputs it as html. I figured it could probably be done using something like preg_replace on a filter or action hook, or something that allows you to process the content before it’s returned as html. Does that make any sense? Any help would be greatly appreciated.

Viewing 2 replies - 1 through 2 (of 2 total)
  • Thread Starter UlukaiThemeDesign

    (@ulukaithemedesign)

    Maybe it can be done with ob_start ?

    https://php.net/manual/en/function.ob-start.php

    Here it is used to clear whitespace from css files:

    <?php
      header('Content-type: text/css');
      ob_start("compress");
      function compress($buffer) {
        /* remove comments */
        $buffer = preg_replace('!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $buffer);
        /* remove tabs, spaces, newlines, etc. */
        $buffer = str_replace(array("\r\n", "\r", "\n", "\t", '  ', '    ', '    '), '', $buffer);
        return $buffer;
      }
    
      /* your css files */
      include('master.css');
      include('typography.css');
      include('grid.css');
      include('print.css');
      include('handheld.css');
    
      ob_end_flush();
    ?>

    How can I do the above with all my WordPress template files? Of course, the ob_start part can go into header.php and the ob_end_flush(); part can go into the footer, that way it’s called in on all pages, right? But how do I change the code so that it cleans out all whitespace from my templates instead of css files?

    Help?

    Thread Starter UlukaiThemeDesign

    (@ulukaithemedesign)

    Okay, so I did this (code below) and it works!

    Still, I’m a complete PHP newbie, is this done the right way?
    It won’t screw anything up, will it?

    header.php

    <?php
    header('content-type:text/html;charset:utf-8');
    ob_start("compress");
    function compress($buffer) {
    	$buffer = str_replace( array( "\n", '  ', '   ' ), '', $buffer );
    	return $buffer;
    }
    ?>

    footer.php
    <?php ob_end_flush(); ?>

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘How do I strip out all whitespace via a filter?’ is closed to new replies.