1. Home
  2. WP User Frontend Pro
  3. Tutorials
  4. Using Action Hook field

Using Action Hook field

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

Step 1: Give the action a name

Action Hook name

Now you can add your own functions on this hook.

Step 2: Binding your functions to the hook

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

/**
* 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 );

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, 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.

/**
 * 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' );

Thats it, easy and fun!

Was this article helpful to you? Yes 20 No 24

How can we help?