Horje
add a span in each title - Wordpress Solution
[Solved] - add a span in each title - Wordpress Solution
Try following codes
in the content of my posts i have some title like that
<h1 style="color:red;font-size:15px;">example of title</h1>
in this case i want to remove the "style" to have
<h1>example of title</h1>
same thing with h1, h2, h3, h4, h5, h6 AND i want to add a span in every h-tag (h1->h6) like that
<h1><span>example of title</span></h1>
i have write this function but that doesn't work where is the mistake ?

function replace_title($content) {
      $pattern1 = "`(<h[1-6])`";
      $pattern2 = "`(<h[1-6])([a-zA-Z0-9\"\'=;:_ -]{1,})>`";
      $pattern3 = "`(<h[1-6])>([^.$]*)(<\/h[1-6]>)`";


      if (preg_match($pattern3, $content)) {//no style inline
      $content = preg_replace($pattern3, '$1><span>$2</span>$3', $content);//add a span
      }

      elseif (preg_match($pattern2, $content)) {//with a style inline
      $content = preg_replace($pattern2, '$1>', $content);//remove the style
      $content = preg_replace($pattern3, '$1><span>$2</span>$3', $content);//add a span
      }
      
      return $content;
}

add_filter('the_title', 'replace_title',1); //Remplacer les titres dans le titre
add_filter('the_content', 'replace_title',1); //Remplacer les titres dans le contenu

------------------------------------------------------------------------ edit 1 : TWO THINGS : 1-remove the style in H-tag if there is a style 2-add a span in each H-tag (h1->h6) and just modify my function ------------------------------------------------------------------------

Solution - 1

try this

add_filter('the_title', 'replace_title',1);
function replace_title($title) {
return '<h1><span>'.$title.'</span></h1>';
}


Solution - 2

I would do it with Jquery:


$('h1,h2,h3,h4,h5,h6').removeAttr('style');
$('h1,h2,h3,h4,h5,h6').wrapInner('<span />');


Solution - 3

you could try this approach:


function replace_title($content) {
  $from=array("<h1>","<h2>","<h3>","</h1>","</h2>","</h3>",);
  $to=array("<h1><span>","<h2><span>","<h3><span>","</span></h1>","</span></h2>","</span></h3>");
  $content=str_replace($from,$to,$content);
  return $content;
}
ps: I updated the function (I switched $to and $from) ;-)


Solution - 4

how about:

<?php the_title( '<h1><span>', '</span></h1>' ); ?>


Solution - 5

If you are okay with jQuery than use below code.. Below code will remove inline styling and add span tags. Place this script after all javascripts so it will load last and if any javascript adding inline style than it will override and remove that too. This is tested and working completely fine. If you want to use jQuery no conflict than change $ to jQuery

Date: 2022-10-21 05:06:08
Category: Wordpress
More for You