Change Tab Labels Using PHPPRO

Sometimes you might want to change a tab label dynamically using PHP prior to the form being rendered on your website.

In this tutorial we show you how to change a tab label 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 change the label of the first tab. Data about each tab is stored in an array called groups. Each group array element is an object. The label is stored in an object variable called label.

To edit the tab label we use the following code:

$form_object->groups[0]->label = 'New Tab Label';

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 ) {

    // Change label of first tab (0 = First tab, 1 = Second tab etc)
    $form_object->groups[0]->label = 'New Tab Label';

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