在WordPress中单击后创建一个新用户

时间:2015-08-13 08:36:42

标签: javascript php jquery ajax wordpress

因此,我正在尝试在WordPress中创建一个插件,该插件将在验证电子邮件后将新用户作为订阅者添加到数据库中。

我有我的插件文件夹,我们称之为'插件'。

在那里我们有index.php,它看起来像这样:

<?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; 
     }

}


?>

然后我们在plugin / js /

中有assests.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);
                });

        }
    });

});

然后还有另一个php文件试图在数据库中创建WP用户。这也可以在根目录中找到:

<?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();
    }

?> 

我需要做些什么来实现这个目标?

1 个答案:

答案 0 :(得分:1)

根据这个,只有你最后一个剪辑需要修复,你可以尝试:

 <?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();
    }

?> 

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

的文档

清理过滤器列表http://php.net/manual/en/filter.filters.sanitize.php

希望它可以帮助你。