The get_background_image() WordPress PHP function retrieves the background image for custom backgrounds.
Usage
$background_image_url = get_background_image();
Parameters
- None
More information
See WordPress Developer Resources: get_background_image
Examples
Setting a post-specific background image
In this example, we check if the current post has a featured image. If so, we set it as the background image. If not, we use the theme’s default background image.
// Declare $post global if used outside of the loop $post = get_post(); // Check if the theme supports Featured Images and 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 background image $page_bg_image_url = get_background_image(); } // Output the <style> tag echo '<style type="text/css" id="custom-background-css-override"> body.custom-background { background-image: url(\'' . $page_bg_image_url . '\'); } </style>';
Adding a background image to a specific page template
This example shows how to use a specific background image on a page template named “custom-page.php.”
if (is_page_template('custom-page.php')) { $custom_background_image_url = 'https://example.com/path/to/image.jpg'; } else { $custom_background_image_url = get_background_image(); } echo '<style type="text/css"> body.custom-background { background-image: url(\'' . $custom_background_image_url . '\'); } </style>';
Setting a default background image for a custom post type
This example sets a default background image for a custom post type named “product” if no custom background is set.
if (get_post_type() == 'product' && !get_background_image()) { $default_product_bg_image_url = 'https://example.com/path/to/default-product-bg.jpg'; } else { $default_product_bg_image_url = get_background_image(); } echo '<style type="text/css"> body.custom-background { background-image: url(\'' . $default_product_bg_image_url . '\'); } </style>';
Displaying a background image only on the homepage
This example shows how to display a background image only on the homepage.
if (is_front_page()) { $homepage_bg_image_url = get_background_image(); echo '<style type="text/css"> body.custom-background { background-image: url(\'' . $homepage_bg_image_url . '\'); } </style>'; }
Adding a background image to a specific category archive page
This example sets a background image for a specific category archive page with the slug “news.”
if (is_category('news')) { $news_category_bg_image_url = 'https://example.com/path/to/news-category-bg.jpg'; } else { $news_category_bg_image_url = get_background_image(); } echo '<style type="text/css"> body.custom-background { background-image: url(\'' . $news_category_bg_image_url . '\'); } </style>';