Site logo

Archived topic

Highlight h2

3 replies · Started by Ricardo on January 26, 2021

Viewing posts 1–4 of 4

Hi,

I want to highlight (mark) all h2 text.

I could use <mark> tag, but is there a way to add that tag to all h2 automatically?

I tried that with css, and figured something like this:

h2{
background-color:#111111;
max-width: max-content;
padding: 0 6px;
margin: 24px 0;
}

But there is something that it doesn't work well:

If the text occupies 2 or more lines, all the text area, not only the text, gets the background color.

Do you have any tip for me?

If this is out of your scope, I tottaly understand.

Thanks in advance,
Ricardo

Hi ideally you would want to insert a <span> tag inside each of your headings simply by writing it in the HTML editor eg.

<h2><span>Some long text here... </span></h2>

But i can see that being a chore. So you could filter the_content and replace all H2's with that markup using a snippet like this:

function add_span_inside_h2($content) {

  // Pattern that we want to match
  $pattern = '/<h2>(.*?)<\/h2>/';

  // match pattern and replace H2 with H2 Span
  $content = preg_replace_callback($pattern, function ($matches) {
    $title = $matches[1];
    $slug = sanitize_title_with_dashes($title);
      return '<h2><span>' . $title . '</span></h2>';
  }, $content);
  return $content;
}

add_filter('the_content', 'add_span_inside_h2');

Then you can style the span within the H2:

h2 {
  max-width: 400px;
}

h2 span {
  background-color: #000;
  color: #fff;
  padding: 10px;
  box-decoration-break: clone;
  -webkit-box-decoration-break: clone;
  line-height: 2;
}

I have added a max-width to the H2 element just for illustration purposes.

Hi,

Thank you very much for your reply. Unfortunately I couldn't get the effect as I needed and didn't want to bother with a customization question.

So I tried to use <mark> in the h2 and with this css, I got the effect I needed:

mark {
background-color: #222222;
color: #fff;
}

Example here: https://beoporto.com/livrarias-para-criancas-no-porto/

And with your reply, now I'm starting to understand the power of filters. Thank you!

Just a question about performance, please:

In practice, does it make any difference to apply a filter adding <mark> instead replacing h2 with span + class or to edit html manually?

Thank you very much!

Adding the HTML to your content is more efficient than using a filter. But i don't think you would see any real world difference in performance. The advantage of the Filter means you don't have to edit HTML :)

This archived topic is closed to new replies.