3

Imagine you put a link in your WordPress post, for example to https://green.example. You also set a link to https://red.example and to https://yellow.example. I would like to make it such that depending on the target URL of a link, a CSS class is automatically assigned to the link.

For example https://green.example should be assigned the class "green", https://red.example the class "red" and so on.

It should be definable for which links these classes should be assigned, not only for exact URLs (like https://green.example/example/hello.php), but also by rules like "for all URLs starting with https://green.example*".

Does anyone know how this can be done in a performance-saving way? Is JavaScript mandatory or can it be done with a WordPress function?

This function should ideally apply to all links, so not only within a post, but also if you use, for example, additional fields through ACF (Advanced Custom Fields).

1 Answer 1

2

This can be done with CSS 3 selectors. You can apply styles when an attribute starts with a value. ^= means "starts with" here.

a[href^="https://green.example/"]{color:white;background-color:green}
a[href^="https://yellow.example/"]{color:black;background-color:yellow}
a[href^="https://red.example/"]{color:white;background-color:red}

Here is a demonstration.

This technique has excellent browser support. 99.78% of users will be able to see it in their browsers.

1
  • Wow, this is an incredibly elegant way. I didn't expect it to be possible simply through CSS. I thought you would have to implement it with javascript or via functions.php. That's awesome :-) Thanks!
    – dajana.s
    Commented Sep 3, 2022 at 22:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.