Pressbooks URL re-write with javascript

I supported the creation of a PressBooks OER textbook at VCU. It’s now getting published as part of a VIVA grant. As part of that, the book is imported into the central VIVA PressBooks site.

They reached out to me indicating that the image links for WP media links were failing on the VIVA site. A bit of looking led to this.

Here is the difference between the link (that fails #1) and the image itself that works (#2).

  1. https://viva.pressbooks.pub/wp-content/uploads/sites/29/2022/05/chapter-1-01.jpg (written as /wp-content/uploads/sites/29/2022/05/chapter-1-01.jpg but resolves to the previous full url)
  2. https://viva.pressbooks.pub/app/uploads/sites/107/2024/06/chapter-1-01.jpg

I believe this is because the image links are/were relative when it was imported and they did not get re-written. So it appends the new base-url, but you can see that the structure is not the same as on the original VCU site (the addition of app in place of wp-content, new site ID (107 instead of 29), new date elements.

I don’t think we have any easy find/replace options because the pattern is dependent on the new file location (assuming we had database access).

Here’s how I’d suggest we fix this if we can put in some custom javascript. I’m waiting to hear back if we can run custom javascript in some way.

This javascript finds the image url (that works) and then replaces the existing broken link with that URL. To make it fully functional, we’d do a querySelectorAll and loop through all the figure elements, but this gives you a rough idea.

See the Pen
Pressbooks url rewrite
by Tom (@twwoodward)
on CodePen.

Leave a Reply