0

I'm brand new at writing WordPress plugins and have tried to find which hook would be appropriate to use when changing the background color for front-end pages. I've tried the_content, stylesheet, and template so far. The stylesheet hook almost works, but causes some pages to not display correctly. Here is the function I've written so far:

function prefix_set_bg_color() {
$prefix_bg_color = get_option( '_crb_box_background' );
?><body style="background-image: none; background-color:<?php echo $prefix_bg_color; ?>"><?php
}
add_action( 'the_content', 'prefix_set_bg_color' ); 

While this does change the background color, it removes all other content from the front end pages.

What would be the most appropriate hook in this situation? Or, is there an easier way to set the background color without interfering with how pages/posts display on the front end?

1
  • I don't think there is a tag that allows you to replace the body tag which is what you're looking to do with the code above. Your body tag already exists (probably in the theme's header.php) and the_content should be used with add_filter rather than add_action. Changing the background colour should really be a theme option rather than a plugin option as plugins, by and large, should be appearance agnostic. I can show you a simple way to do this in header.php. Commented Mar 10, 2021 at 3:58

1 Answer 1

0

After some further trial and error I discovered the action hook the_post which seems to work in this situation. It updates the background color while still allowing the rest of the page/post content to display.

2
  • You should not be outputting a <body> tag in the middle of the page. That’s invalid HTML. If you want to change the background colour just use CSS in Customize > Additional CSS. Commented Mar 6, 2021 at 4:55
  • I'm trying to do it from a plugin. If one of WordPress's APIs offers a way to modify the Additional CSS option, I am unfamiliar with how to do so. I'm brand new at plugin writing, so I might be missing something obvious to others. I don't know what the standard practice is for modifying CSS through plugins.
    – ei3j2iao
    Commented Mar 6, 2021 at 5:49

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.