Search code examples
wordpressninja-forms

Adding custom fields to Ninja Forms


I'm trying to add a custom field to Ninja Forms (v. 3.3). Can't find a complete example anywhere.

Digging through the code it seems that the filter 'ninja_forms_register_fields' would do the trick but I can't get it to run anywhere.


Solution

  • Here is how to create/add new Ninja Forms field type (keep in mind this code should be moved into separate WordPress plugin).

    First we need to hook into ninja_forms_register_fields:

    add_filter( 'ninja_forms_register_fields', array($this, 'register_fields'));
    

    Then define method register_fields (inside plugin class):

    public function register_fields($actions) {
        $actions['blah'] = new NF_CustomPlugin_Fields_Blah(); 
    
        return $actions;
    }
    

    Last step is to declare NF_CustomPlugin_Fields_Blah class:

    class NF_CustomPlugin_Fields_Blah extends NF_Fields_Textbox {
        protected $_name = 'blah';
        protected $_section = 'common'; // section in backend
        protected $_type = 'textbox'; // field type
        protected $_templates = 'textbox'; // template; it's possible to create custom field templates
    
        public function __construct() {
            parent::__construct();
    
            $this->_nicename = __( 'Blah Field', 'ninja-forms' );
        }
    }