函数文档

get_background_image()

💡 云策文档标注

概述

get_background_image() 函数用于检索自定义背景图像,返回背景图像的 URL 字符串。它通过 get_theme_mod() 获取主题修改值,并支持默认图像回退。

关键要点

  • 函数返回字符串类型的背景图像 URL
  • 内部调用 get_theme_mod('background_image', get_theme_support('custom-background', 'default-image')) 实现
  • 与自定义背景功能相关,常用于主题开发中处理背景图像

代码示例

// 检查是否有特色图像,否则使用主题背景图像作为回退
$post = get_post();
if ( current_theme_supports('post-thumbnails') && has_post_thumbnail($post->ID) ) {
    $page_bg_image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full');
    $page_bg_image_url = $page_bg_image[0];
} else {
    $page_bg_image_url = get_background_image();
}

📄 原文内容

Retrieves background image for custom background.

Return

string

Source

function get_background_image() {
	return get_theme_mod( 'background_image', get_theme_support( 'custom-background', 'default-image' ) );
}

Changelog

Version Description
3.0.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Use Theme Background Image as Fallback if No Featured Image Exists

    This example could be used to detect whether the current Page/Post has a Featured Image set – if so, it will use the Featured Image as the page background, if not it will use the current active theme’s default background image. As is, this should be used in the of the page template, just after the call to wp_head() :

    // Declare $post global if used outside of the loop.
    $post = get_post();
    
    // check to see 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 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>