If your API returns complex data or you need to format your data in a particular way, then you will most likely need to use the template tag method of outputting data.
Using the template tag is infinitely more flexible than the shortcode but can pose a few hurdles:
- You need to modify the code within your theme
- You need to understand FTP or cPanel to upload new/modified files
- It is prone to coding errors and 1 mistake can crash your entire website
Luckily there are a couple of methods we can use that allows us to run PHP code without having to worry about these 3 issues. Both methods involve using a PHP snippet plugin. You are free to use any snippet plugin that you like, but we have found the plugin below to work very well for what we need.
Plugin: “Code Snippets”
Plugin URL: https://wordpress.org/plugins/code-snippets/
With this plugin we can run either sitewide code or code that is output with a shortcode.
Option 1 – Create a shortcode snippet
This option will be useful for being able to add complex PHP code or complex formatting pages via a shortcode. It essentially turns complex PHP code into a shortcode.
Creating a shortcode snippet using this plugin:
- Click on Add New
- Select the Content (HTML) option
- Add your PHP code
- Click Save
- You will then see the shortcode that can be used in any widget, post or page.
Option 2 – Create sitewide snippet
This option will be useful for running code sitewide, such as when needing to run your API after a form submission like in these examples:
Instructions for creating a sitewide PHP snippet using this plugin:
- Click on Add New
- Select the Functions (PHP) option
- Add your PHP code – the code is from here
- Click Save
This code will now run everywhere on your site, waiting for a form submission from Contact Form 7.