0

In a pre-Gutenberg site, I have a shortcode with roughly the following structure:

function generate_new_member_form() {
    ob_start(); ?>
   // a form
   // to generate this form there is some code that uses objects or functions 
   // only available in the front end
  <?php return ob_get_clean();
} 

add_shortcode('new-member-form', 'generate_new_member_form');

For whatever it's worth, the code has to do with Woocommerce checkout fields, and I get fatal errors when I try to edit a page that has the shortcode [new_member_form] such as "Call to a member function get() on null". But I don't think the problem has to do with Woocommerce

Is there a way to prevent Gutenberg from trying to run any of this code in the backend? I would like to be able to edit the page and see just [new_member_form] with no attempt to display the shortcode.

3
  • Your shortcode should include checks to make sure of any dependencies are available. Then the shortcode loading in the backend wouldn’t be a problem. Nov 30, 2019 at 5:59
  • I was hoping I could avoid doing that. I'm sure there are plenty of cases where you want to run the shortcode in the backend, but this is not one of them (I can see the part of the form before the errors in the editor, but I don't really care about seeing it, since I cannot modify it in the editor)
    – adelval
    Nov 30, 2019 at 6:12
  • It doesn't matter where the shortcode is intended to be used. You should always code that way. It's surely a couple of lines of code that would solve this problem and make your code considerably less prone to bugs. Nov 30, 2019 at 8:25

1 Answer 1

1

Use it like this, this defined('REST_REQUEST') will help you to disable running on the backend gutenberg block editor

function generate_new_member_form() {
if(defined('REST_REQUEST')) return;
    ob_start(); ?>
   // a form
   // to generate this form there is some code that uses objects or functions 
   // only available in the front end
  <?php return ob_get_clean();
} 

add_shortcode('new-member-form', 'generate_new_member_form');

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.