Using Action Hook field

A- A+

Action Hook Field is a very extensive solution when you are building your form controls. When the built-in custom fields in the plugin aren't helpful, you can render your fields in the form using the Action Hook field.

Step 1: Give the action a name

Action Hook name

Now you can add your functions to this hook.

Step 2: Binding your functions to the hook

Now that we've got a hook name, we can bind our functions to this action hook

[php] /**
* Add the input field to the form
*
* @param int $form_id
* @param null|int $post_id
* @param array $form_settings
*/
function render_my_awesome_hook( $form_id, $post_id, $form_settings ) {
    $value = ”;

    if ( $post_id ) {
        $value = get_post_meta( $post_id, ‘your_meta_key', true );
    }
    ?>

    <div class=”wpuf-label”>
        <label>A demo field</label>
    </div>

    <div class=”wpuf-fields”>
        <input type=”text” name=”my_custom_field” value=”<?php echo esc_attr( $value ); ?>”>
    </div>
    <?php
}

add_action( ‘my_awesome_hook', ‘render_my_awesome_hook', 10, 3 );
[/php]

Here we are adding a function render_my_awesome_hook to our hook my_awesome_hook. We get 3 parameters with that action

  • $form_id – The form ID of the form
  • $post_id – The post ID. If we are creating a new post, it becomes NULL. If we are editing a post, it gives us the post ID
  • $form_settings – The settings of our current form as an array

So basically we are adding text input field to that form. We can add more complex fields if we want

Step 3: Saving our input

Now that we've added our form input, it's time to save those data when submitting the form. WP User Frontend gives you two useful action hooks: 1) when a post is submitted, and 2) When a post is updated.

1) When a post is submitted, the wpuf_add_post_after_insert action runs.
2) When a post is updated, the wpuf_edit_post_after_update action runs.

So we bind a function to those hooks and save our input.

[php] /**
 * Update the custom field when the form submits
 *
 * @param type $post_id
 */
function update_my_brand_new_hook( $post_id ) {
    if ( isset( $_POST[‘my_custom_field'] ) ) {
        update_post_meta( $post_id, ‘your_meta_key', $_POST[‘my_custom_field'] );
    }
}

add_action( ‘wpuf_add_post_after_insert', ‘update_my_brand_new_hook' );
add_action( ‘wpuf_edit_post_after_update', ‘update_my_brand_new_hook' );
[/php]

That's it—easy and fun!