Wrap element with in any number of elements with PHP

Can I use a similar technique to ‘wrap’ my everything in the body with another div?

Absolutely. Almost everything is possible. But you’re going to have to do something a little hackish.

The the_content filter doesn’t actually filter the content of the entire page. That particular filter is used throughout WordPress to filter a variety of different contents.

Unfortunately, there isn’t a good way to filter the entire page.

One way to accomplish this would be to use ob_start() and ob_get_clean() attached to appropriate hooks. We need to hook into before anything is output to the page and start an output buffer. Then we need to hook in at the last possible moment and get the buffer.

Then we can do something with the content. Your regex was close, but not quite right.

In your functions.php, add the following:

//* Hook into WordPress immediately before it starts output
add_action( 'wp_head', 'wpse_wp', -1 );
function wpse_wp() {

  //* Start out buffering
  ob_start();

  //* Add action to get the buffer on shutdown
  add_action( 'shutdown', 'wpse_shutdown', -1 );
}

function wpse_shutdown() {

  //* Get the output buffer
  $content = ob_get_clean();

  //* Do something useful with the buffer

  //* Use preg_replace to add a <section> wrapper inside the <body> tag
  $pattern = "/<body(.*?)>(.*?)<\/body>/is";
  $replacement="<body$1><section class="new-master">$2</section></body>";

  //* Print the content to the screen
  print( preg_replace( $pattern, $replacement, $content ) );
}

Should I use a similar technique to ‘wrap’ my everything in the body with another div?

It depends. A better, faster way to accomplish this would be to edit the template files. Since you state that you don’t have access to the template files, then I believe that something like this would be your only option.

Leave a Comment