Using Template Tag Functions in a block
-
Reporting an issue when using a template tag function in a WP block.
I’ve created a custom block that uses tablepress_print_table() to display a table, according to some parameters that the user enters for the block. This is an alternative to the shortcode that TablePress provides.
If I add the block to a post/page in the editor, it works fine and displays the table as expected. Now I publish the post and it looks good on the front end.
Problem – when I then go to edit the post/page, WordPress crashes “Fatal error: Uncaught Error: Call to undefined function tablepress_print_table() …”
After some investigation, I’ve found that WP invokes the block more than once when it starts up the editor. I added some code to my block and to the TablePress run() function to output a trace to a file. Here’s what I get when I click to edit the page.
In TablePress function run() - Controller selected: admin_ajax In TablePress function run() - Controller selected: admin In TablePress function run() - Controller selected: admin_ajax In TablePress function run() - Controller selected: admin In Block render - function does not exist <strong>(Could crash here)</strong> In TablePress function run() - Controller selected: frontend In TablePress function run() - Controller selected: frontend In Block render - function found OK In TablePress function run() - Controller selected: frontend In TablePress function run() - Controller selected: frontend In TablePress function run() - Controller selected: frontend In TablePress function run() - Controller selected: frontend In TablePress function run() - Controller selected: frontend In TablePress function run() - Controller selected: frontend In TablePress function run() - Controller selected: frontend In Block render - function found OK In TablePress function run() - Controller selected: frontend In TablePress function run() - Controller selected: frontend In TablePress function run() - Controller selected: admin_ajax In TablePress function run() - Controller selected: admin In TablePress function run() - Controller selected: admin_ajax
So in my block code, I have to use
if (function_exists('tablepress_print_table')
because when it’s first invoked, TablePress is using the “admin” controller.I have to say that I’m very surprised that the block is called up three times, and that TablePress is called in so many times, just when I click to edit a page!
As I say, this is mainly to report the issue so that others can be aware. I am OK with the workaround, which is to use
if (function_exists('tablepress_print_table')
in my block – then it works and displays the table in the editor as I want it to.
- The topic ‘Using Template Tag Functions in a block’ is closed to new replies.