如何在WordPress的PHP环境中调用JSON API获取player数据并制作top scorers standing widget?
Hey there! Let's walk through how to build your Premier League top scorers widget in WordPress using the Goalserve API, plus cover the essentials of working with JSON APIs in a WordPress PHP environment.
WordPress officially recommends using wp_remote_get() for external API calls instead of native functions like file_get_contents(). It’s more reliable, supports HTTP request configuration, error handling, and integrates smoothly with WordPress’s caching system.
The basic workflow goes like this:
- Initiate the request: Use
wp_remote_get()with your API URL and optional config (like timeout settings) - Validate the response: Check for request errors and confirm a successful HTTP status code
- Decode JSON: Convert the response body into a PHP array/object using
json_decode() - Process data: Extract the fields you need, and handle edge cases (like empty responses or unexpected data structures)
First, replace mytoken in your API URL with your actual API key. Here’s a reusable function to fetch the top scorers data:
function get_top_scorers_data() { // Replace with your real Goalserve API token $api_token = 'your-actual-api-token'; $api_url = "https://goalserve.com/getfeed/{$api_token}/topscorers/1204?json=1"; // Configure request settings to avoid site slowdowns $args = array( 'timeout' => 10, 'user-agent' => 'WordPress Top Scorers Widget/1.0' ); // Send the API request $response = wp_remote_get($api_url, $args); // Check for request errors if (is_wp_error($response)) { error_log('Top Scorers API Error: ' . $response->get_error_message()); return false; } // Verify HTTP success $response_code = wp_remote_retrieve_response_code($response); if ($response_code !== 200) { error_log('Top Scorers API HTTP Error: ' . $response_code); return false; } // Decode JSON response into an associative array $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); // Validate the expected data structure if (!isset($data['topscorers']['tournament']['player'])) { error_log('Top Scorers API: Unexpected data structure'); return false; } return $data['topscorers']['tournament']['player']; }
Key Notes:
- Always sanitize and validate data to avoid security risks
- The
json_decode($body, true)flag converts the JSON into an associative array, making it easier to access fields like@nameor@goals - Error logs help debug issues without breaking the frontend
Turn the data-fetching function into a WordPress widget so you can add it to any sidebar or widget area:
// Register the widget with WordPress add_action('widgets_init', function() { register_widget('Top_Scorers_Widget'); }); // Define the widget class class Top_Scorers_Widget extends WP_Widget { public function __construct() { parent::__construct( 'top_scorers_widget', 'Top Scorers Standing', array('description' => 'Displays Premier League Top Scorers from Goalserve API') ); } // Frontend display logic public function widget($args, $instance) { echo $args['before_widget']; // Display custom widget title if (!empty($instance['title'])) { echo $args['before_title'] . apply_filters('widget_title', $instance['title']) . $args['after_title']; } // Fetch top scorers data $top_scorers = get_top_scorers_data(); // Handle empty/failed data if (!$top_scorers) { echo '<p>Top scorers data is unavailable right now. Please try again later.</p>'; echo $args['after_widget']; return; } // Render the top scorers list echo '<div class="top-scorers-list">'; foreach ($top_scorers as $player) { echo '<div class="top-scorer-item">'; echo '<span class="position">' . esc_html($player['@pos']) . '.</span>'; echo '<span class="player-name">' . esc_html($player['@name']) . '</span>'; echo '<span class="team">(' . esc_html($player['@team']) . ')</span>'; echo '<span class="goals">' . esc_html($player['@goals']) . ' Goals</span>'; if ((int)$player['@penalty_goals'] > 0) { echo '<span class="penalty-goals">(' . esc_html($player['@penalty_goals']) . ' pens)</span>'; } echo '</div>'; } echo '</div>'; echo $args['after_widget']; } // Backend settings form public function form($instance) { $title = !empty($instance['title']) ? $instance['title'] : 'Premier League Top Scorers'; ?> <p> <label for="<?php echo esc_attr($this->get_field_id('title')); ?>"><?php _e('Widget Title:'); ?></label> <input class="widefat" id="<?php echo esc_attr($this->get_field_id('title')); ?>" name="<?php echo esc_attr($this->get_field_name('title')); ?>" type="text" value="<?php echo esc_attr($title); ?>"> </p> <?php } // Save backend settings public function update($new_instance, $old_instance) { $instance = array(); $instance['title'] = (!empty($new_instance['title'])) ? sanitize_text_field($new_instance['title']) : ''; return $instance; } }
- Cache Data: Avoid hitting the API on every page load by using WordPress transients. Add this to the
get_top_scorers_data()function:// Check for cached data first $transient_key = 'top_scorers_data'; $cached_data = get_transient($transient_key); if ($cached_data) { return $cached_data; } // ... (existing API request code) ... // Cache the data for 1 hour (3600 seconds) set_transient($transient_key, $data['topscorers']['tournament']['player'], 3600); - Style the Widget: Add custom CSS to your theme’s
style.cssto make the list look clean (e.g., align positions, names, and goals neatly) - Secure Your API Key: Store your token in WordPress’s custom options instead of hardcoding it. Add a simple settings page to let admins input the key safely
内容的提问来源于stack exchange,提问作者Adam Sari

