Including Jupyter Notebooks in WordPress

So, you’ve just exported your Jupyter notebook as a .html file, and are about to embed it in your WordPress post. While it may be tempting to just copy and paste the generated html code in a custom html code block, you’ll probably find out pretty quickly that doing so entirely messes up the css of your theme, leading to issues like the sidebar loading at the bottom of the page instead of at the side, fonts and font colours being altered in unexpected ways, etc.

This is my way of embedding Jupyter notebooks in WordPress posts. It uses iframes, and so far, it has not caused any significant issues yet. (I tried it with the Astra theme)

Note that this guide assumes that you haven’t made any changes to your nbconvert settings or added any functions to your functions.php file to aid in rendering notebooks properly. With the steps below, you don’t have to.

Step 1: “Pre-format” your Jupyter notebook html file

The html file generated by nbconvert works pretty well straight out of the box (as expected). However, if you happen to have a cell with a long line of code, doesn’t render a scrollbar if you chuck it in an iframe, and instead just outright clips.

We can fix that by adding a line into the css definitions in the html file to add a scrollbar to any cells that need it.

I have written a simple python script to automate this task:

import sys

from tempfile import mkstemp
from shutil import copymode, move
from os import fdopen, remove

from tkinter import Tk
from tkinter.filedialog import askopenfilename

Tk().withdraw()

try:
    old_file_path = sys.argv[1]
except IndexError:
    old_file_path = askopenfilename()

found_body = False
file_handler, new_file_path = mkstemp()
with fdopen(file_handler, 'w', encoding="utf-8") as new_file:
    with open(old_file_path, encoding="utf-8") as old_file:
        for line in old_file:
            # debug note: use print(repr()) to show newline characters
            if line == ".CodeMirror.cm-s-jupyter {\n":
                found_body = True
                #print('found a body')
            
            if "color: var(--jp-content-font-color1);" in line and found_body == True:
                new_file.write(line)
                new_file.write('  overflow: auto;\n')
                found_body = False
                continue

            new_file.write(line)

copymode(old_file_path, new_file_path) #copy permissions
remove(old_file_path)
move(new_file_path, old_file_path)

Just run the script, choose the html file when prompted.

WARNING: this script modifies the html file, save a copy if necessary.

Step 2: Upload the html file to your media in WordPress

This step is pretty straightforward. Once you’ve uploaded the html, click on it in your library and copy the file URL, we’ll be using it shortly.

Step 3: Set up the iframe in your blog post

At the location within your post where you want to include the Jupyter notebook, add a Custom HTML block. Then, paste in the following code, not forgetting to change the src string in the iframe tag to the link you copied in step 2.

Important: Delete all the stuff up to /wp-uploads, otherwise you will get cross-origin errors.

Example: if the link you obtained in step 2 is https://example.com/wp-uploads/test.html, the src parameter in the iframe tag should be /wp-uploads/test.html

<script type="application/javascript">

function resizeIFrameToFitContent( iFrame ) {

   iFrame.height = iFrame.contentWindow.document.body.scrollHeight + 80;
}

window.addEventListener("load", function(){ //this prevents issues of the script getting wrong values for the scroll height due to the document not having been loaded completely yet


    var iFrame = document.getElementById( 'Jupyter-Mainframe' );
    resizeIFrameToFitContent( iFrame );


    
} );

</script>

<iframe src="your file URL here" id="Jupyter-Mainframe" scrolling="yes" width="100%">
</iframe>

And there you go! You should now have a Jupyter notebook fully embeded in your post.

Note:

In order to get LaTeX elements to render correctly, you need to install the MathJax-LaTeX plugin for WordPress.

Leave a Comment

Your email address will not be published. Required fields are marked *