I had a requirement to export all my WordPress blog posts into a nicely formatted PDF file and so I looked at plugins that were available to do the job, of which there are a few. I tried some and none worked for me giving no output at all so I decided I would roll my own. Here’s how you can use that code to download your posts to PDF too. You can see an example of the output at the bottom of the post.
In order to access the WordPress API and run the code you need to set up an application password as follows.
Setting Your WordPress Application Password
Go to your WordPress Dashboard and edit the user that you want to have access. I created a new user with only subscriber access rather than using my main admin account as it only needs read-only access.
Go to the Application Passwords section and give your application a name, preferably spelling it correctly unlike I did! Then click Add New Application Password.
Your application password will now be displayed on the screen. Make a note of this as you will need it to pass to the script.
Dealing with large posts and low memory
I ran into a couple of issues with the script. The first was that FPDF holds the output in memory until it is done which means for very large sites (my personal blog runs to nearly 800 posts) you need lots of memory. To get around this I added an FPDF extension that writes each page to the file on disc as soon as it is done rather than holding it in memory which did the trick.
The second issue was that it takes quite a long time to run the script and so the PHP was timing out. Getting around this was as simple as just running the script from the command line which it is now setup to do.
Calling the code
Running the script is simple. Download and unzip all the code from the GitHub repository and from a terminal command prompt move into the folder. You can then run the command as follows:
php index.php "URL of your site" "name of the WordPress user" "your Application Password" "local folder where you would like the output placed"
For the last parameter, the location of the output, if you just want it in the same place as the code select “.”.
When running you will see output similar to the following. The last step, “Writing output file” takes quite a while so don’t worry if it doesn’t seem to be responding.
If you want to learn more about the code itself have a look at the README file. I should point out that it currently doesn’t work very well with code blocks but I will look to see if I can improve that.
I hope that you find the script useful.