Display custom_background outside wp_head()

My theme is a very small one page theme which really doesn’t need all the scripts, so I’ve created a few options to remove wp_head() and wp_footer() so the user can choose if they want to enable or disable those.

However, my site does use the custom_background() feature which is placed in the wp_head() so when they disable wp_head(), they will also remove the background.

Is there a way to place the custom_background() code outside the wp_head()?

2 Answers
2

custom_background() places the CSS to wp_head() as you mentioned so to get those CSS as if you don’t have wp_head() in your header, these tweaks from the core files would help:

function wpse_228588_background_image_css() {
    $background_styles="";
    if ( $bgcolor = get_background_color() )
        $background_styles .= 'background-color: #' . $bgcolor . ';';

    $background_image_thumb = get_background_image();
    if ( $background_image_thumb ) {
        $background_image_thumb = esc_url( set_url_scheme( get_theme_mod( 'background_image_thumb', str_replace( '%', '%%', $background_image_thumb ) ) ) );

        // Background-image URL must be single quote, see below.
        $background_styles .= ' background-image: url(\'' . $background_image_thumb . '\');'
            . ' background-repeat: ' . get_theme_mod( 'background_repeat', get_theme_support( 'custom-background', 'default-repeat' ) ) . ';'
            . ' background-position: top ' . get_theme_mod( 'background_position_x', get_theme_support( 'custom-background', 'default-position-x' ) );
    }
    return $background_styles; // CSS
}

Usage:

<style type="text/css" media="all">body{<?php echo wpse_228588_background_image_css(); ?>}</style>

Leave a Comment