必應的圖片選的很棒,根據其他作者的代碼二次改進了下,可以在首頁鋪滿整個頁面。
考慮到兼容性問題,不同的主題之間適配難度較大,就不做進插件功能了,大家可以自取代碼,二次修改使用
效果

代碼
// 獲取必應每日圖片的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>
body {
background-image: url('{$bing_image_url}');
}
</style>";
?>
<style>
body {
position: relative;
margin: 0;
padding: 0;
background-repeat: no-repeat;
}
body:after {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
pointer-events: none;
z-index: -1;
/* 確保偽元素在背景圖像下面 */
}
</style>
<?php
echo $css;
}
}