Let me start by saying, I love Ninja Forms. It’s incredibly easy to use, and best of all, it’s free! While my love affair with Ninja Forms still burns deep, there was one thing that was making my life just a little bit more difficult than it needed to be.

The issue showed itself when I used the export tool to add the forms I created on my local development environment to a staging version of the site.  I was working on a site as a part of a team and the staging site was our source of record.  Ninja Forms automatically assigns an ID number to each form and uses that number to add various ID’s to different elements in the form including the form wrapper.  These ID’s are useful for targeting individual forms. However, the problem arises when dealing with multiple environments.  The ID on my local environment did not always match the ID on the staging environment.  This is not an issue if you are the only one controlling content since you can simply import/export the whole database but it can become a real pain when importing/exporting the forms individually.

ninja-forms-blog

What I wanted to do was have the ability to add a custom ID or class to the outer most div of my Ninja Form.  In the image above, you can see that an ID is assigned based off of the form ID number and the common class of “ninja-forms-cont” gets added to all forms created with Ninja Forms.  I searched high and low in the form tools for a way to assign a custom class to the whole form as you can do for individual fields but had no luck.

Let’s Hack this thing!

After some research I learned that you could tap into some of the Ninja Forms functionality using the WordPress add_filter function.  I didn’t want to update the plugin files directly since any plugin update would wipe out my changes.  Here’s what I came up with.


//Ninja Forms -- Adds class to the form wrapper based on form title
function ninja_wrap_class($wrap_class, $form_id){
	$form_title = Ninja_Forms()->form( $form_id )->get_setting( 'form_title' );
	$form_title = strtolower($form_title);
	$form_title = str_replace(' ', '-', $form_title);
	$wrap_class .= ' ninja-wrap-' . $form_title;

	return $wrap_class;
}
add_filter( 'ninja_forms_cont_class', 'ninja_wrap_class', 10,2 );

I did a search through the plugin files to find out how to access the form title. From there, I used some PHP functions to take the title and modify it to the correct syntax to be added as a class. I then appended that class to the class already given to all Ninja Forms form wrappers.

Here’s the resulting code:
ninja-forms-custom-class

My form title “Share Your Story” gets added as a class to the form container allowing me to target the form for CSS or JS without having to target the auto-iterated form ID number.  Now I can make iterations to my form locally and export them without having to worry about my form ID’s not matching on my other environments.

Leave me a comment if this helps you out on your next project.