Date Tags d3.js

In this article, I will explain how I normally proceed with emebedding a d3.js data visualization (but it could be any kind of javascript enabled complex content) in wordpress for my clients (I am not using wordpress on this blog, because I find it too heavy for my taste). As every wordpress installation is unique, I try to be as independent as possible from wordpress. That is why:

  • we won't use any plugin (they may break)
  • we will minimize the number of file to upload
  • and we will use an iframe to be sure we don't run into any naming conflict that could impact the css or javascript

1. Prepare your visualization

We want to have only 1 or 2 files:

  • the html page with internal stylesheet and embedded javascript code
  • the data file (csv, json...) containing the data (unless you are fetching it from some api).

Keeping the data separated make it easier if a change is required in the data. We could also externalize some text from the visualization if required.

As I prefer to work with separate files for html css and javascript, the embedding is actually done in my build process using gulp-inline-source.

Also make sure to have javascript load the file from the same relative path as we don't have much control on the file location with this method, e.g.

d3.csv("file.csv")

2. Upload the files in wordpress

In the admin page, go to Media Library and click add new to add the files.

Click on the HTML file, a popup with details will appear. Copy the value of the URL field somewhere (we will use it just after).

You will notice that the file are uploaded in a directory depending on the current month, so be careful on updates.

3. Create a new page/ post and add

Now create a new page or post and switch to HTML mode.

<iframe
  style="border: 0px;"
  src="[The URL of your html file goes here]"
  scrolling="no"
  width="100%"
  height="500px">
</iframe>

Settings:

  • style: we need to remove the borders
  • scrolling: we want to make sure no scrolling bar will appear

Then you have some decision to take on the iframe size (height and width). I like to put the width to 100% so it can adjust to the width of a standard post as rendered in the final user's screen. and put a height that should allow for a proper rendering. The visualization code is then responsible for the proper use of available width. You force the width for a simpler visualization code, but then you want to be sure you will have the space you ask for (think about mobiles).

Publish/Preview the post and voilĂ !

Note: if you are running a free site on wordpress.com, this will not work due to limitations with files uploads and iframes.


Do you want to learn how to create better dashboard and UIs for, in particular for IoT and Wearables? Pre-order the Elements of Dashboard Design book now for a special prelaunch price

Dashboard design for IoT and wearables