I want to get WordPress featured image in pseudo elements. I’ve used it in inline style using following code
<?php
$thumb_url = wp_get_attachment_image_src(get_post_thumbnail_id($whatWeDo_post->ID), 'single-post-thumbnail' );
?>
<div style="background-image: url(<?php echo $thumb_url[0]; ?>);">
But I want to use it in pseudo elements
Option 1
Your main concern here is caching. You don’t want to write the
background-image
style into your external.css
file because it will probably change on every page. But you don’t want to clog up your main HTML file with lots of extra inline styles.Your best bet is to split off just what you don’t want cached (the
background-image
and the rest of the styles). We want to inline just what shouldn’t be cached, and leave the rest as an external.css
file.Say the styles relevant to your Featured Images container are something like this:
Just leave your
.css
file exactly the same format (don’t use.css.php
), but pull out thebackground-image
line.Then in the header, place this:
Bonus – Another Option Just for Fun
The second option is to use a
.php
file with a.css
HTTP header. I like to name my files something like:Advantages
This lets you use WordPress variables and data, as well as the entire power of PHP, directly in your stylesheet. But it’s still sent to the browser as a
.css
file, so you can enqueue it like normal. It’s the easiest to implement. Note, be sure to include the globalpost
object.Disadvantages
Do you use resource caching? If you
.css
files are cached, you’re going to run into a problem because the file won’t change on each page. In your specific case, the Featured Image will be different on each page. If you don’t cache, it should be fine, but you absolutely should be caching, so you should probably skip this option.Tweak on Bonus Option
If you like Option 1 but you do cache (which you should), you can take a middle ground. Create your file the same as above, something like:
Instead of enqueueing it the official way using
wp_enqueue_style
, you can read the file with PHP’sinclude
function.Create a function in your
functions.php
file:Then in your header, add:
The CSS will be pulled in and written inline.
Advantages
Caching won’t be a problem. Also you won’t have a large render blocking
.css
resource. Plus the advantages from Option 1.Disadvantages
You are including potentially a massive chunk of CSS inline. Possibly too much.
This is pulling from Mr Lister’s comment, but here’s a method of doing this. It’s not the best way to structure the html, but it should work:
I’m not sure if you’ll run into some browser compatibility issues with older browsers and the tag outside of the , but it should work in modern browsers.