使用 Bing 每日图片作为网站首页背景

使用 Bing 每日图片作为网站首页背景,也是来自于上一个主题的想法。其实方法相对简单,即利用必应公开的 API 调用每日图片再设置为 Background 就行了,不过我在使用时还叠加了网格和黑色的半透明像素,这样才能让白色文字看得更清晰不至于混乱。废话不说直接上代码您各位参考:

// 获取必应每日图片的URL
function get_bing_daily_image_url() {
    // 必应API URL,用于获取每日图片的JSON数据
    $bing_api_url = 'https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1';
    
    // 设置缓存键值,用于存储和检索图片URL
    $cache_key = 'bing_daily_image_url';
    
    // 尝试获取缓存中的图片URL
    $img_url = get_transient($cache_key);

    // 如果缓存中没有找到图片URL,则请求必应API
    if (!$img_url) {
        // 使用WordPress函数发送HTTP GET请求到必应API
        $response = wp_remote_get($bing_api_url);
        
        // 确保HTTP请求没有返回错误
        if (!is_wp_error($response)) {
            // 获取HTTP请求的响应体内容
            $body = wp_remote_retrieve_body($response);
            
            // 解析JSON格式的响应体
            $data = json_decode($body, true);

            // 如果数据中含有图片URL,则进行处理
            if (!empty($data['images'][0]['url'])) {
                // 生成完整的图片URL
                $img_url = 'https://cn.bing.com' . $data['images'][0]['url'];
                
                // 将图片URL存储到缓存中,并设置过期时间为一天
                set_transient($cache_key, $img_url, DAY_IN_SECONDS);
            }
        }
    }

    // 如果获取到了图片URL则返回它,否则返回主题目录下的默认图片
    return $img_url ? $img_url : get_template_directory_uri() . '/images/blog-overview-bg.webp';
}

// 将必应每日图片添加到首页的背景
add_action('wp_head', 'bing_daily_image_homepage_css');

// 添加自定义CSS到前端主页的 <head> 部分
function bing_daily_image_homepage_css() {
    if (is_front_page()) {
        $bing_image_url = get_bing_daily_image_url();
        // CSS样式被格式化,使其具有更可读的结构
        $css = "
        <style>
            #grve-theme-content {
                background-image: url('{$bing_image_url}');
                position: relative;
            }
            #grve-theme-content:after {
                content: '';
                position: absolute;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0,0,0,0.4) url('https://staticfile.shephe.com/wp-content/themes/impeka/images/graphics/pattern.png') repeat;
                pointer-events: none;
            }
        </style>";
        
        echo $css;
    }
}

我在以上代码中加入了非常详细的注释,机智如你肯定一看就懂了……如果要看实用效果请打开 Kevin's Space 首页,其中的黑色网格图按此下载,以上。


使用Bing每日图片作为网站首页背景
使用 Bing 每日图片作为网站首页背景
1500 1000 Kevin's
「使用 Bing 每日图片作为网站首页背景」有 2 条评论
  • Dabenshi
    05/09/2024 at 09:24 回复

    这个好,没准我会用的到

  • obaby
    05/08/2024 at 18:46 回复

    bing图片质量还是蛮高的

发表评论

请输入关键词…