Marco V
Marco V

Reputation: 2633

Create a new user upon click within WordPress

So I'm trying to create a plugin in WordPress that will add a new user to the database as a subscriber after the email has been validated.

I've got my plugin folder we shall call 'plugin'.

In there we have index.php which looks like this:

<?php


/**
 *  Set up a PHP function to handle the AJAX request.
 **/

    add_action('wp_ajax_nopriv_add_subscriber','add_subscriber');
    add_action('wp_ajax_add_subscriber','add_subscriber');

/**
 * Initialize widgets
 **/

    add_action('widgets_init', 'more_subscribers_init');

 /**
 * Register widget
 **/

    function more_subscribers_init() {
        register_widget(more_subscribers);
    }

/**
 * Create the widget class 
 */
class more_subscribers extends WP_Widget {

    function more_subscribers() {
        $widget_options = array(
            'classname' => 'ms_class',
            'description' => 'Shows a field where the user can enter email address'
        );

        $this->WP_Widget('ms_id', 'More Subscribers', $widget_options);
    }

    /**
    * Show widget form in Appearance/Widgets 
    */

    function form($instance){
        $ms_email = array('title' => 'Your email address');
        $instance = wp_parse_args( (array) $instance, $defaults);

        $title = esc_attr($instance['title']);

        echo '<p>Title <input type="text" class="widefat" name="'.$this->get_field_name('title').'" value="'.$title.'" /></p>';
    }

    /**
     * Save the widget 
     */

     function update ($new_instance, $old_instance){
         $instance = $old_instance;
         $instance['title'] = strip_tags($new_instance['title']);
         return $instance;         
     }

     /**
     * Show widget in post/page 
     */

     function widget ($args, $instance){
        extract($args);
        $title = apply_filters('widget_title', $instance['title']);

        echo $before_widget;
        echo $before_title.$title.$after_title;

        echo '<input type="email" name="FirstName" placeholder="Your email address" id="input_fld">';
        echo '<input type="Submit" name="submit_email" value="Submit" id="submit_btn">';        

        //print widget
        echo $after_widget; 
     }

}


?>

Then we have assests.js located in plugin/js/

//Random function to test if jQuery is working
$(document).ready(function() {
    //$('aside#ms_id-2 h2').hide();

//email validate function
function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}

//Execute a php script on click event using an ajax request

    $('#submit_btn').click(function(){
        var entered = $('#ms_id-2 > input#input_fld').val();
        if (isValidEmailAddress(entered) == false) {
            alert('Sorry, the email you entered is invalid. Please try again.');
        } else {
            ajaxData = {
                action: add_subscriber,
                email: entered
            }
            $.ajax({
                url: 'wp-content/plugins/more-subscribers/addEmail.php',
                type:'POST',
                data: ajaxData
                }).done(function(msg){
                    alert('Thank you!');
                    console.log(ajaxData);
                });

        }
    });

});

And then there is another php file which attempts to create the WP user in the database. This can also be found in the root directory:

<?php

    add_action('wp_ajax_nopriv_add_subscriber','add_subscriber');
    add_action('wp_ajax_add_subscriber','add_subscriber');

 /* Add email to database */
    function addEmail(){
        $email = htmlentities($_POST['email']);
        if(wp_create_user($email,'7777777',$email)) echo 'OK';
        die();
    }

?> 

What do I need to do to get this working?

Upvotes: 0

Views: 79

Answers (1)

DFayet
DFayet

Reputation: 881

According that only your last snipped needs to be fixed, you could try :

 <?php
        
      add_action('wp_ajax_nopriv_add_subscriber','add_subscriber');
      add_action('wp_ajax_add_subscriber','add_subscriber');
        
      // Add the new subscriber
      function add_subscriber(){
          // it's not a good idea to use htmlentities for a username
          $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
    
          // Just a check, if the mail exists
          if( $email != "" ) {

              // Does the username exists
              if( null == username_exists( $email ) ) {

                   // Generate the password and create the user, better than use 7777777, don't forget to give the password to the user
                   $password = wp_generate_password( 7, false );
                        
                   $userdata = array(
                       'user_login'  =>  $email,
                       'user_pass'   =>  $password,
                       'user_email'  =>  $email,
                       'role'        => 'subscriber'
                    );

                    $user_id = wp_insert_user( $userdata ) ;
    
                    // Check if the user has been created
                    if( !is_wp_error($user_id) ) {

                        echo 'OK';

                    }// if

                } //if

            }// if
            
        die();
    }
        
?> 

Docs for filter_input() http://php.net/manual/en/function.filter-input.php

List of sanitize filters http://php.net/manual/en/filter.filters.sanitize.php

Hope it can helps you.

Upvotes: 1

Related Questions