header_image() with CSS
-
01-03-2021 - |
Question
Forgive my ignorance in the matter, as i've only just started delving into wordpress. But, i was wondering if theres a way to use header_image()
in CSS.
So, for example my functions.php
is allowing me to enqueue a php file with the header:
<?php header("Content-type: text/css; charset: UTF-8;"); ?>
Allowing me to manipulate my theme with it. Now, I want my header image to be editable through the customizer instead of the user having to navigate the CSS files. So for example:
.headerimg {
/* Set a specific height */
height: 700px;
/* Create the parallax scrolling effect */
background-image: url("<?php header_image()?>");
background-attachment: fixed;
background-position: center;
background-repeat: no-repeat;
background-size: cover;
/* Styling */
border-top: 3px solid transparent;
border-bottom: 3px solid #0099FF; }
This of course, doesn't work, and throws the error:
Fatal error: Uncaught Error: Call to undefined function header_image() in [filepath]
So, in short - is there some way to accomplish this effect? Or will i have to rely on just using straight up <img>
elements
Solution
No, in general, it's not possible to use php in CSS. But you can set background image in php file. Like..
<div class="headerimg" style="background-image: url(<?php echo header_image(); ?>)"></div>
Then in CSS file using class you can set all the other properties you need like height, width, background-position and so on.
OTHER TIPS
In order to access the header_image()
function like that, you would have to bootstrap the entirety of WordPress from the file that is generating your stylesheet.
A better option would be to stick with a static .css file but extract the dynamic portion for use within wp_add_inline_style()
. When all is said and done, it might look something like:
// Generate inline scripts and styles and attach them to the appropriate script handles.
function my_inline_scripts() {
// header_image() prints the image - we want it as a string.
$image = get_header_image();
// Can be false - it might be better to set a fallback here...
if ( ! $image ) {
return;
}
// First param should be the handle of your theme stylesheet.
wp_add_inline_style( 'my-theme-style', ".headerimg { background-image: url(\"{$image}\"); }";
}
add_action( 'wp_enqueue_scripts', 'my_inline_scripts' );