wordpressmetadataninja-forms

Update extra user data through Ninja Forms on WordPress


I have created a form using Ninja Forms, where users give some answers for some questions and create a score. I have calculated the scores in Ninja Forms, and I need to update that score as a user field. I have created the field using Profile Extra Fields plugin. I've seen the Custom Form Action and Hook Tag part, but I have no idea how to write the code and implement it. Can you guys help me?


Solution

  • If your intention to do it programatically here is one way of doing it (you can probably paste this in your functions.php, but preferably you should create custom plugin):

    First register a new action:

    add_filter( 'ninja_forms_register_actions', 'register_my_nf_action' );
    function register_my_nf_action( $actions ) {
        $actions['my_action_name'] = new MyActionClass();
        return $actions;
    }
    

    Then create a class:

    class MyActionClass extends NF_Abstracts_Action {
        protected $_name     = 'my_action_name';
        protected $_timing   = 'late';
        protected $_priority = '100';
    
        public function __construct() {
            parent::__construct();
    
            $this->_nicename = esc_html__( 'My Action', 'text-domain' );
        }
    
        public function save( $action_settings ) {
            // You don't need to implement anything here
        }
    
        public function process( $action_settings, $form_id, $data ) {
            // Check if user is logged in (WordPress)
            if ( is_user_logged_in() ) {
                $user_id = get_current_user_id();
                // some logic here
                update_user_meta( $user_id, 'meta_key', 'your_meta_value' );
            }
    
            return $data;
        }
    }
    

    Make sure to add custom action to your form and save the form before testing it.