How to upload a thousand .txt files to WordPress

Understandably, txt is not everyones favourite format – not that most people even have a favourite format in the first place. Due to its simplicity, however, it is the base format that many Content Management Systems will export your posts & pages to, as it includes all the text that you provided without any of the formatting that the CMS used to take care of.

Unfortunately, WordPress neglects to provide an easy way to get all your lovely .txt files into posts or pages. I have, therefore, spent a few hours brushing up on my bash to bring you this.

#!/bin/bash
for filename in *.txt
do
  echo $(basename "'${filename}'" .txt)
  wp post create "${filename}" --post_type=page --post_author=3 --post_title="$(basename "${filename}" .txt)"
done

Just to be clear, I was working on an Ubuntu Linux server. If you are working in a different environment, YMMV.

To make this work,

  1. install the WordPress CLI.
  2. Change directory to the location of your WordPress installation. Mine is at /var/www/html/
  3. Make a new directory in which you can put all your lovely .txt files.
  4. Put your .txt files in said directory.
    I compressed all of mine using ZIP, then used SCP to get that file into the server before finally unzipping in the right place. Remember to delete your .zip once you are done with it.
  5. Run the above shell script
sh txt2wp.sh

There you have it! In just a few minutes, all your .txt files will be on your shiney new WordPress website as pages. If you want them to be posts, just change the --post_type to post.

You might also like to run this script in a screen session, particularly if you have many .txt files. This will allow you to turn your laptop off without interrupting the process on the server side.

Leave a Reply

%d bloggers like this: