use add_action in a shortcode (gravity form – WordPress)

After some discussing in the comments, I can surmise that this is your situation:

  1. You have functionality for processing a user registration in some way when a form is submitted.
  2. You need a way in the CMS to specify which forms this processing needs to happen for.

What it looks like you’re attempting to do is add a shortcode to the page with a matching form ID so that when the form is submitted the processing occurs for that form.

There are several problems with this:

  1. Shortcodes are intended for displaying dynamic contnet inside a post or page. They are not intended for back-end events like form processing.
  2. When a Gravity Form is submitted, it is processed before the page content is reloaded. This means that it’s too late to attempt to hook into the form submission hook, because it has already run and finished.

The ‘proper’ way to develop this would be to develop a “feed”, which is how Gravity Forms supports developers providing a way to add their functionality to specific forms via the UI. The documentation for creating custom feed types is available here. In your case you would put your registration processing into the process_feed method of your custom feed.

However, as you’ve suggested, it is quite a lot of work to create an add-on feed. So, I’m going to suggest a workaround:

  1. Add a hidden field to the forms that you wish to process.
  2. Hook into gform_after_submission for all forms and check for this hidden field. If the hidden field is present, process the registration.

So, for the first step, add a Hidden field to the forms that you need to be processed. Give it a label that makes sense for you. I’ll assume “App Benutzer”, just based on the shortcode name.

Now, this is what your code will be:

function msk_gform_process_user_registration_MB( $entry, $form ) {
    $fields = $form['fields'];

    // Check every field in the form.
    foreach ( $fields as $field ) {
        // If our hidden field has been added to this form, process the user registration.
        if ( $field->label="App Benutzer" ) {
            // Process user registration here.
        }
    }
}
add_action( 'gform_after_submission', 'msk_gform_process_user_registration_MB', 10, 2 );

So this solves the problem of allowing non-technical users a way to tell Gravity Forms which forms the user registration should be processed for: They just need to add a Hidden field with the label “App Benutzer”.