Advertisement
secumbu

WP Block Theme div to main

Oct 10th, 2024
42
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.37 KB | None | 0 0
  1. <?php
  2.  
  3. function replace_content_div_with_main() {
  4.     ob_start(function($buffer) {
  5.         $dom = new DOMDocument();
  6.         $dom->loadHTML(mb_convert_encoding($buffer, 'HTML-ENTITIES', 'UTF-8'), LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
  7.  
  8.         $xpath = new DOMXPath($dom);
  9.         $divs = $xpath->query('//div[contains(@class, "wp-site-blocks")]');
  10.  
  11.         if ($divs->length > 0) {
  12.             foreach ($divs as $div) {
  13.                 $containsHeader = $xpath->query('.//header', $div)->length > 0;
  14.                 $containsFooter = $xpath->query('.//footer', $div)->length > 0;
  15.  
  16.                 if (!$containsHeader && !$containsFooter) {
  17.                     $main = $dom->createElement('main');
  18.                     $main->setAttribute('class', $div->getAttribute('class'));
  19.                    
  20.                     while ($div->firstChild) {
  21.                         $main->appendChild($div->firstChild);
  22.                     }
  23.                    
  24.                     $div->parentNode->replaceChild($main, $div);
  25.                     break;
  26.                 }
  27.             }
  28.         }
  29.         $buffer = $dom->saveHTML();
  30.         return $buffer;
  31.     });
  32. }
  33. add_action('wp_loaded', 'replace_content_div_with_main');
  34.  
  35. function end_output_buffer() {
  36.     if (ob_get_length()) {
  37.         ob_end_flush();
  38.     }
  39. }
  40. add_action('shutdown', 'end_output_buffer', 999);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement