Celebrate WordCamp Europe - 30% OFF! Use coupon WC30 - View Details

Setting Which Post ID to Populate With Using PHPPRO

In this tutorial we show you how to change the ‘Post ID’ setting found in Form Settings > Data > Populate Using Action by using a simple PHP script. The script would typically reside in the functions.php file in your theme folder (always use the child theme for custom configuration if your theme allows it).

Creating The Filter

First we are going to use the following function to create a new filter in WordPress:

add_filter( string $tag, callable $function_to_add, int $priority = 10, int $accepted_args = 1 )

You can learn more about this function by clicking here.

The tag we will use is a WS Form filter called:

wsf_pre_render_<form_id>

For example, to process the form_object for form ID 123, the tag would be:

wsf_pre_render_123

The second parameter provides WordPress with the callback function through which $form_object  will flow.

The third parameter determines the priority, we can just leave that with a number of 10.

The fourth parameter defines how many parameters are passed to the callback function, in this case it is 2; $form_object and $preview.

The complete statement looks something like this:

add_filter( 'wsf_pre_render_123', 'wsf_pre_render_callback', 10, 2 );

This filter is applied prior to the form being rendered.

Creating The Callback Function

The callback function is a called by WordPress to filter the form.

Two parameters are passed to the callback function:

$form_object – A complete object containing the form itself.

$preview – Whether the form is being rendered in preview mode or not (We’ll ignore this parameter in this tutorial).

Here is a simple example of the callback function:

// My callback function for tag wsf_pre_render_123
function wsf_pre_render_callback( $form_object, $preview ) {

    // Do something with $form_object here
    // ...

    // Return the form object back to WS Form
    return $form_object;
}

As you can see, we return $form_object back to WS Form at the end of the function after making changes to it.

For the purpose of this tutorial we’re going to edit the ‘Post ID’ setting. This done by setting the action_post_form_populate_post_id meta key.

$form_object->meta->action_post_form_populate_post_id = 234;

You would change ‘234’ to be the post ID you want to use.

Putting It All Together

The final code you would add to your functions.php file can be found below:

// Add a filter for form ID 123
add_filter( 'wsf_pre_render_123', 'wsf_pre_render_callback', 10, 2 );

// My callback function for tag wsf_pre_render_123
function wsf_pre_render_callback( $form_object, $preview ) {

    // Set the 'Post ID' setting to 234
    $form_object->meta->action_post_form_populate_post_id = 234;

    // Return the form object back to WS Form
    return $form_object;
}