Custom Widget with External API Integration

Create a widget that displays data from an external API.

<?php
class Weather_Widget extends WP_Widget {
    function __construct() {
        parent::__construct(
            'weather_widget',
            __('Weather Widget', 'text_domain'),
            array('description' => __('Displays weather information from an external API.', 'text_domain'))
        );
    }

    public function widget($args, $instance) {
        $api_key = 'your_api_key';
        $location = !empty($instance['location']) ? $instance['location'] : 'London';
        $response = wp_remote_get("http://api.weatherapi.com/v1/current.json?key=$api_key&q=$location");
        $data = wp_remote_retrieve_body($response);
        $weather = json_decode($data);

        if (isset($weather->current)) {
            echo $args['before_widget'];
            echo $args['before_title'] . esc_html($location) . $args['after_title'];
            echo '<p>Temperature: ' . esc_html($weather->current->temp_c) . '°C</p>';
            echo '<p>Condition: ' . esc_html($weather->current->condition->text) . '</p>';
            echo $args['after_widget'];
        }
    }

    public function form($instance) {
        $location = !empty($instance['location']) ? $instance['location'] : __('London', 'text_domain');
        ?>
        <p>
            <label for="<?php echo $this->get_field_id('location'); ?>"><?php _e('Location:', 'text_domain'); ?></label>
            <input class="widefat" id="<?php echo $this->get_field_id('location'); ?>" name="<?php echo $this->get_field_name('location'); ?>" type="text" value="<?php echo esc_attr($location); ?>" />
        </p>
        <?php
    }

    public function update($new_instance, $old_instance) {
        $instance = array();
        $instance['location'] = (!empty($new_instance['location'])) ? strip_tags($new_instance['location']) : '';
        return $instance;
    }
}

function register_weather_widget() {
    register_widget('Weather_Widget');
}
add_action('widgets_init', 'register_weather_widget');
?>

Post Comment