I am modifying a WordPress template and haven’t done so in about 5 years.
I want to be able to change the background color of posts by inputing a color value in a custom field in the WordPress back end. Specifically I want to be able to have multiple background colors for different posts, I don’t want the latest post to determine the background color of the entire site.
For example, I might enter "CCCCCC" to specify that the page background for that particular post be grey.
I can see how to use the post_meta function (and others) to print that information into the HTML, but can’t see an elegant way to use that to modify the CSS.
How would you suggest that’s done?
One challenge is that the custom value is called from the loop. If I want to change the color of the entire page it’s better to change the background color of the body, but that would need to happen in the header.
I’d really like to avoid JS. Is there a light, smart way of doing this?
Obviously this is how a value can be passed to the page. However I want to modify the CSS.
$key_1_value = get_post_meta( get_the_ID(), 'Background color', true );
// Check if the custom field has a value.
if ( ! empty( $key_1_value ) ) {
echo $key_1_value;
}
3
Answers
I don’t know if you haven’t done CSS in 5 years, or just WordPress theming in general, but my recommendation would be to use CSS variables (custom properties). The CSS function
var()
accepts a fallback value as the second parameter, do use that as your default and then give the variable a meaningful name that you can optionally set later.Demo: https://codepen.io/cjhaas/pen/ExdExvR
WordPress already injects the tag and categories into the
<article>
block for your articles.So you could give a special tag to the articles you want to have different background colors without any need to change any wordpress/php code.
So you just need to change the css based on the variable, am I correct? So you could use inline-style css, for example