You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在WordPress个人作品集站点搭建带weather API的特色天气页面?

嘿,这个带天气互动的作品集页面想法超棒!我来一步步教你实现这个功能,全程基于WordPress原生功能,不用折腾复杂插件:

一、前期准备
  • 选个靠谱的免费天气API:找支持IP自动定位+当前天气查询的API(很多主流天气服务商都有免费额度),先去注册拿到API密钥,记好它的接口文档(比如获取天气的接口地址、返回参数里的气温字段)。
  • 在WordPress后台新建页面:页面标题设为“Weather”,slug改成weather(方便访问),先留空,后面加内容。
二、写代码实现核心逻辑

推荐你把代码做成短代码,这样可以直接在页面里调用,而且比直接改页面模板灵活。你可以把下面的代码放到主题的functions.php里,或者更稳妥的做法是新建一个自定义插件(避免主题更新丢失代码)。

function weather_photo_shortcode() {
    // 1. 缓存处理:避免频繁调用API,缓存1小时
    $weather_data = get_transient('visitor_weather_data');
    if (!$weather_data) {
        // 获取访客IP
        $visitor_ip = $_SERVER['REMOTE_ADDR'];
        // 替换成你的API地址和密钥,这里示例用占位符
        $api_url = "https://api.example.com/weather?ip={$visitor_ip}&appid=你的API密钥";
        
        // 用WordPress原生函数发起请求
        $response = wp_remote_get($api_url);
        if (is_wp_error($response)) {
            return '<p>抱歉,暂时无法获取天气信息😢</p>';
        }
        
        $weather_data = json_decode(wp_remote_retrieve_body($response), true);
        // 缓存1小时(3600秒)
        set_transient('visitor_weather_data', $weather_data, 3600);
    }

    // 2. 提取气温(根据你的API返回字段调整,比如这里假设是main.temp)
    $current_temp = isset($weather_data['main']['temp']) ? $weather_data['main']['temp'] : 20;
    // 定义寒冷阈值,比如低于10°C算冷
    $is_cold = $current_temp < 10;

    // 3. 准备照片数组:可以是媒体库的附件ID,或者主题目录下的图片路径
    // 示例1:用媒体库照片,先给照片加个分类(比如“寒冷照片”“温暖照片”)
    $photo_args = array(
        'post_type' => 'attachment',
        'post_mime_type' => 'image',
        'posts_per_page' => -1,
        'tax_query' => array(
            array(
                'taxonomy' => 'media_category', // 假设你给媒体库加了这个分类法
                'field' => 'slug',
                'terms' => $is_cold ? 'cold-photos' : 'warm-photos'
            )
        )
    );
    $photos = get_posts($photo_args);

    // 如果没找到照片,用默认图
    if (empty($photos)) {
        $default_img_url = get_template_directory_uri() . '/assets/default-' . ($is_cold ? 'cold' : 'warm') . '.jpg';
        $photo_html = '<img src="' . esc_url($default_img_url) . '" alt="默认照片" style="max-width:100%;height:auto;">';
    } else {
        // 随机选一张照片
        $random_photo = $photos[array_rand($photos)];
        $photo_url = wp_get_attachment_image_url($random_photo->ID, 'large');
        $photo_html = '<img src="' . esc_url($photo_url) . '" alt="' . esc_attr($random_photo->post_title) . '" style="max-width:100%;height:auto;">';
    }

    // 4. 生成提示文本
    $tip_text = $is_cold ? '今天气温有点低,看看我裹得严严实实的日常😆' : '天气刚刚好,来看看我的户外随拍~';

    // 5. 组装最终HTML
    $output = '<div class="weather-photo-container">';
    $output .= '<p class="weather-tip">' . $tip_text . '</p>';
    $output .= $photo_html;
    $output .= '</div>';

    return $output;
}
add_shortcode('weather_photo', 'weather_photo_shortcode');
三、代码里的关键细节说明
  • API替换:把代码里的$api_url换成你实际用的API地址,注意调整气温字段的提取逻辑(不同API返回的字段名可能不一样,比如有的是temp_c表示摄氏度)。
  • 照片管理:如果不想给媒体库加分类,也可以直接把照片放到主题的某个文件夹里,用glob()函数读取文件路径,比如:
    $photo_dir = get_template_directory() . '/assets/photos/' . ($is_cold ? 'cold' : 'warm') . '/';
    $photo_files = glob($photo_dir . '*.jpg');
    if (!empty($photo_files)) {
        $random_file = $photo_files[array_rand($photo_files)];
        $photo_url = get_template_directory_uri() . '/assets/photos/' . ($is_cold ? 'cold' : 'warm') . '/' . basename($random_file);
    }
    
  • 缓存优化:用transient缓存天气数据,避免每分钟都调用API,超出免费额度。如果需要实时更新,可以缩短缓存时间,比如15分钟(900秒)。
  • 隐私提示:如果担心访客介意IP定位,可以在页面开头加一句“我们会通过你的IP获取当前天气,用于展示个性化内容,不会存储你的位置信息”,更贴心。
四、最后一步:在页面里调用短代码

回到你新建的Weather页面,在编辑器里输入[weather_photo],发布页面后访问你的域名/weather,就能看到根据当前天气展示的随机照片啦!

如果遇到API调用失败的情况,记得检查API密钥是否正确、网络是否能正常访问API,还有WordPress的wp_remote_get是否被服务器防火墙限制(可以联系主机商确认)。

内容的提问来源于stack exchange,提问作者Pavel Maloș

火山引擎 最新活动