Consuming an external API in WordPress?

A short primer on WordPress development that might help or might confuse you:

The main thing to keep in mind: it’s all just PHP. And also: don’t edit the core files of WordPress, because you will get in trouble when you update to a newer version later. The only code you should edit is that of plugins and of themes.

If you only need to add something to an existing page, it might work to just edit the right theme file. However, if you need to do something advanced (and adding an extra “view”, like at a specific URL, is more advanced in WordPress), you need to add the code at a place that will be loaded earlier in the WordPress boot process.

The reason for this is that WordPress always does a post query for you, based on the URL. It you go to /category/banana/, it will query for posts of category banana and load the correct template file where you only have to loop over and display them. However, if you go to /custom-view/, WordPress will probably not find any post and load the 404 template – giving you no easy way to recover!

Some people solve this by creating “stub pages”: they create a Page in WordPress where the content is not important, only the template is: there they do whatever fancy thing they want to do. This is hackish, but it works. The clean way would be to define extra rewrite rules, that let WordPress know that /custom-view/ is a valid URL, but that something else should happen there.

If you want to do this, you need to hook into the core WordPress system. The important part here is hook into, not modify. WordPress has actions and filters. An action is just an announcement (“Hey, we’re currently writing the <head> tag. Do you want to add anything too?”). A filter allows you to modify a variable (“This is the post title. If you want to modify it, return a new value”). Of course, the trick now is to know which actions and filters you should use. This depends on the way you choose (stub pages or new rewrite rules), so I won’t go into details here.

You define the actions and filters you want to use in a plugin file or in the functions.php file of your theme. They are special in that they are loaded while WordPress is booting, so before the main query is executed and so on. A plugin file is just a PHP file, placed in the wp-content/plugins/ directory, with a special header so WordPress can read its name and display it in the administration area where you can enable and disable it (so you can leave the plugin in the directory but temporarily disable it).

Leave a Comment