Creating a World Cup 2014 WordPress Widget

Tweet

Football (soccer) is undoubtedly the most popular and prestigious sporting game in the world. It is globally governed by the Fédération Internationale de Football Association (FIFA), the sport’s international administrative body.

The FIFA World Cup, usually referred to simply as the World Cup is a competition hosted every four years, contested by the senior men’s national teams of qualified countries. This year’s tournament hosted in Brazil is currently ongoing.

World Cup 2014

While reading Hacker News, I stumbled upon an API for the World Cup that scrapes current match results and outputs match data as JSON.

You can get the following World Cup data from this API:

  • All match data, updated every minute
  • Today’s matches
  • Tomorrow’s matches
  • Matches for any country by entering their FIFA Code
  • The current match if a match is happening, otherwise nothing.
  • Results for group stage (wins, losses, draws, goals_for, goals_against)

I love football and I know a lot of us do too. Due to my busy schedule, I always find myself asking friends about the match schedule.

To eliminate this barrier, I decided to build a Match Fixtures widget for WordPress that displays a list of matches to be played today and tomorrow, powered by the World Cup API.

If you want to jump ahead of the tutorial below, you can view a a demo of the Fifa fixtures widget here and download the widget plugin files here.

Building the Fixtures Widget

The Fixture widget to be developed at the end of this tutorial will be a tabbed widget; the first tab displays matches for today and the second tab displays matches for the next day.

World Cup Widget

Let’s get started with widget plugin development.

First, we need to include the plugin header. Without the header, WordPress won’t recognize the widget plugin.

<?php
/*
  Plugin Name: FIFA World Cup Widget
  Plugin URI: http://tech4sky.com
  Description: Fifa World Cup Widget
  Version: 1.0
  Author: Agbonghama Collins
  Author URI: http://tech4sky.com
 */

Building Widgets in WordPress is easy and straightforward. Extend the standard WP_Widget class and include the required widget class methods, and finally register the widget.

Create a child-class extending the WP_Widget class.

class Fifa_WC_Fixtures extends WP_Widget {
// ...

Give the widget a name and description using the __construct() magic method.

function __construct() {
    parent::__construct(
        'fifa', // Base ID
        __('Fifa World Cup', 'text_domain'), // Name
        array('description' => __('World Cup Fixtures for Today and Tomorrow\'s Games', 'text_domain'),) 
    );
}

The class method matches_today(), shown below, queries the World Cup API, retrieves the matches to be played today and displays it together with the time of play.

If no match is scheduled for that day, a No match for today message is shown.

public function matches_today() {
    $today_matches = file_get_contents('http://worldcup.sfg.io/matches/today');
    $today_matches_data = json_decode($today_matches);

    echo ' <div><ul class="orange">';
    if (Count($today_matches_data) > 0) {

        foreach ($today_matches_data as $match) {
            echo '<li>';
            echo '<a class="widget-list-link"><strong>';
            echo $match->home_team->country;
            echo '</strong><span>vs</span><strong>' . $match->away_team->country;
            echo '</strong><span>' . (substr($match->datetime, 11, 2) + 5) . ':00' . '</span>';
            echo '</a>';
            echo '</li>';
        }
    } else {
        echo '<li>';
        echo 'No match for today';
        echo '</li>';
    }
    echo '</ul></div>';
}

Similar to the matches_today() class method above, the matches_tomorrow() method display matches to be played the following day:

public function matches_tomorrow() {
    $tomorrow_matches = file_get_contents('http://worldcup.sfg.io/matches/tomorrow/');
    $tomorrow_matches_data = json_decode($tomorrow_matches);

    echo ' <div><ul class="green">';
    if (Count($tomorrow_matches_data) > 0) {
        foreach ($tomorrow_matches_data as $match) {
            echo '<li>';
            echo '<a class="widget-list-link"><strong>';
            echo $match->home_team->country;
            echo '</strong><span>vs</span><strong>' . $match->away_team->country;
            echo '</strong><span>' . (substr($match->datetime, 11, 2) + 5) . ':00' . '</span>';
            echo '</a>';
            echo '</li>';
        }
    } else {
        echo '<li>';
        echo 'No match for today';
        echo '</li>';
    }

    echo '</ul></div>';
}

The back-end widget settings form is created using the form() method. The fixture widget will consist of a form field that will contain the title of the widget.

public function form($instance) {
   if (isset($instance['title'])) {
        $title = $instance['title'];
    } else {
        $title = __('World Cup Fixtures', 'text_domain');
    }
    ?>
    <p>
        <label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label> 
        <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" 
               name="<?php echo $this->get_field_name('title'); ?>" 
               type="text" value="<?php echo esc_attr($title); ?>">
    </p>
    <?php
}

World Cup Widget

When data are entered into the form widget fields, they need to be saved to the database for reuse. The update() method sanitizes and saves the data to the database.

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

    return $instance;
}

Next is the widget() method that displays the match fixtures at the front-end of WordPress.

public function widget($args, $instance) {
    ?>
    <script type="text/javascript" >
    $('document').ready(function(){
        $('#flip-container').quickFlip();

        $('#flip-navigation li a').each(function(){
            $(this).click(function(e){
                $('#flip-navigation li').each(function(){
                    $(this).removeClass('selected');
                });
                $(this).parent().addClass('selected');
                var flipid=$(this).attr('id').substr(4);
                $('#flip-container').quickFlipper({ }, flipid, 1);

                e.preventDefault();
            });
        });
    });
    </script>

    <?php
    $title = apply_filters('widget_title', $instance['title']);

    echo $args['before_widget'];
    if (!empty($title))
        echo $args['before_title'] . $title . $args['after_title'];

    echo '<div id="flip-tabs" >
    <ul id="flip-navigation" >
        <li class="selected"><a href="#" id="tab-0" >Today</a></li>
        <li><a href="#" id="tab-1">Tomorrow</a></li>
    </ul>
    <div id="flip-container" >';
    $this->matches_today();
    $this->matches_tomorrow();

    echo '</div>';
    echo '</div>';
    echo '</div>';

    echo $args['after_widget'];
}

Let me briefly explain what the codes in widget() does. The JavaScript code adds a tabbing and flipping effect to the widget. The matches_today() and matches_tomorrow() methods that return the matches for today and tomorrow also get included for display in the WordPress front-end.

Our fixture widget class Fifa_WC_Fixtures need to be registered using the widgets_init hook for it to be recognizable by WordPress.

function register_fifa_widget() {
    register_widget('Fifa_WC_Fixtures');
}

add_action('widgets_init', 'register_fifa_widget');

We still need to include jQuery and the QuickFlip library to get the tab and flipping effect in the widget working and also the widget CSS.

function fifa_widget_lib() {
    wp_enqueue_style('fifa-widget', plugins_url('styles.css', __FILE__));
    wp_enqueue_script('fifa-widgets', plugins_url('js/jquery.js', __FILE__));
    wp_enqueue_script('fifa-widget-js', plugins_url('js/jquery.quickflip.js', __FILE__));
}

add_action('wp_enqueue_scripts', 'fifa_widget_lib');

View a demo of the Fifa fixtures widget.

Conclusion

We are done coding the World Cup Fixtures widget. To further understand how the widget was built and how to implement it on your WordPress site, download the widget plugin, which includes the jQuery, Quickflip, and stylesheet files.

I hope this helps some of you in learning how to build WordPress widgets and in enjoying this year’s World Cup. Let me know your thoughts in the comments.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • http://martinbean.co.uk/ Martin Bean

    What copyright implications does this have? As I imagine the data will be the copyright of FIFA.

    • LouisLazaris

      If FIFA went after someone because of this (and I highly doubt they would care, after all, it’s free advertising) then they would go after the website that hosts the API. The guy who built it discusses its origin here, but he doesn’t seem to say anything about the possibility of copyright infringement. Of course, that doesn’t mean there isn’t a problem. So, I guess, use at your own risk. But my guess is it’s fine.

      • http://martinbean.co.uk/ Martin Bean

        That doesn’t fill me with confidence. I ask because the Football Association, who oversees football in the UK, is very stringent on how FA copyrighted data (i.e. match fixtures and results) are used. I would have thought FIFA, the global body for football, would share the same—or an even stricter—stance.

        • LouisLazaris

          Well, if that were the case, then the API creator would have been notified with a take-down notice or something. Like I said, I don’t know if there would be a problem, but if there were, it would be with the API. In other words, it wouldn’t really matter what anyone did with the API, because if the API goes down, then all the resources using it go down, too.