get_background_image()
Gets the URL of the background image set in the theme settings (in the customizer).
In order to set a background image, support for such an image must be enabled for the theme. This is done with the function add_theme_support('custom-background'). After enabling this option, a background image can be set in the customizer:
Use background_image() when you need to immediately output the URL to the screen.
Also see the similar function for getting the color get_background_color() and background_color().
Different theme options related to the theme background:
$position_x = get_theme_mod( 'background_position_x', get_theme_support( 'custom-background', 'default-position-x' ) ); $position_y = get_theme_mod( 'background_position_y', get_theme_support( 'custom-background', 'default-position-y' ) ); $size = get_theme_mod( 'background_size', get_theme_support( 'custom-background', 'default-size' ) ); $repeat = get_theme_mod( 'background_repeat', get_theme_support( 'custom-background', 'default-repeat' ) ); $attachment = get_theme_mod( 'background_attachment', get_theme_support( 'custom-background', 'default-attachment' ) );
No Hooks.
Returns
String. URL of the background image
Usage
get_background_image();
Examples
#1 Demo
$bg_image = get_background_image(); echo $bg_image; // http://example.com/wp-content/uploads/2015/04/image.jpg
#2 Display the URL in the css styles
<style>
body.custom-background {
background-image: url( '<?php background_image(); ?>' );
}
</style> #3 Use background image as fallback when the post thumbnail is not specified
This example shows how to use a post thumbnail as page background and, if the post picture is not set by default, take a picture from the theme settings:
<head>
<meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php bloginfo('charset'); ?>" />
<?php
if ( is_singular() ) {
wp_enqueue_script( 'comment-reply' );
}
wp_head();
// declare $post global if used outside of the loop
global $post;
// check to see if the theme supports Featured Images and if one is set
if ( current_theme_supports( 'post-thumbnails' ) && has_post_thumbnail( $post->ID ) ) {
// specify desired image size in place of 'full'
$page_bg_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'full' );
$page_bg_image_url = $page_bg_image[0]; // this returns just the URL of the image
}
else {
// the fallback – our current active theme's default bg image
$page_bg_image_url = get_background_image();
}
// And below, spit out the <style> tag...
?>
<style type="text/css" id="custom-background-css-override">
body.custom-background {
background-image: url('<?php echo $page_bg_image_url; ?>');
}
</style>
</head>
Changelog
| Since 3.0.0 | Introduced. |
get_background_image() get background image code WP 6.9.1
function get_background_image() {
return get_theme_mod( 'background_image', get_theme_support( 'custom-background', 'default-image' ) );
} 