如何在网站前端显示WordPress用户注册表格?


30

如何在我的博客的前端显示WordPress用户注册表单(该表单显示在“ www.mywebsite.com/wp-register.php”页面中)?

我已经定制了注册表。但是不知道如何在前端页面中调用该表单。任何支持都是非常有用的帮助。

提前致谢。:)


我发现的最佳解决方案是Theme My Login插件
wyrfel 2011年

文章提供了有关如何创建自己的前端注册/登录/密码恢复形成了马丽娟的教程。或者,如果您正在寻找插件,那么我以前使用过这些插件,并且可以推荐它们:
-Ajax

来自Cosmolabs的Cristian发布了一个很棒的教程,其中包含源文件,使您能够构建前端用户配置文件,登录和注册模板。
菲利普

Answers:


33

该过程涉及2个步骤:

  1. 显示前端表格
  2. 保存提交数据

我想到了三种显示前端的不同方法:

  • 使用内置的注册表格,编辑样式等使其更“像前端”
  • 使用WordPress页面/帖子,并使用简码显示表单
  • 使用不与任何页面/帖子相关联但由特定网址调用的专用模板

对于这个答案,我将使用后者。原因如下:

  • 使用内置的注册表单可能是一个好主意,使用内置的表单进行深度自定义可能非常困难,而且如果还想要自定义表单字段,那么痛苦会增加
  • 结合使用WordPress页面和短代码,并不是那么可靠,而且我认为不应该将shorcode用于功能,而仅用于格式化等。

1:建立网址

我们所有人都知道,WordPress网站的默认注册表格通常是垃圾邮件发送者的目标。使用自定义网址有助于解决此问题。另外,我还想使用一个可变的 url,即注册表格的url不应该总是相同,这使垃圾邮件发送者的生活更加艰难。技巧是通过在URL中使用随机数来完成的:

/**
* Generate dynamic registration url
*/
function custom_registration_url() {
  $nonce = urlencode( wp_create_nonce( 'registration_url' ) );
  return home_url( $nonce );
}

/**
* Generate dynamic registration link
*/
function custom_registration_link() {
  $format = '<a href="%s">%s</a>';
  printf(
    $format,
    custom_registration_url(), __( 'Register', 'custom_reg_form' )
  );
}

使用此功能很容易在模板中显示注册表格的链接,即使该注册表格是动态的。

2:识别URL,Custom_Reg\Custom_Reg类的第一个存根

现在我们需要识别URL。为了方便起见,我将开始编写一个类,稍后将在答案中完成:

<?php
// don't save, just a stub
namespace Custom_Reg;

class Custom_Reg {

  function checkUrl() {
    $url_part = $this->getUrl();
    $nonce = urlencode( wp_create_nonce( 'registration_url' ) );
    if ( ( $url_part === $nonce ) ) {
      // do nothing if registration is not allowed or user logged
      if ( is_user_logged_in() || ! get_option('users_can_register') ) {
        wp_safe_redirect( home_url() );
        exit();
      }
      return TRUE;
    }
  }

  protected function getUrl() {
    $home_path = trim( parse_url( home_url(), PHP_URL_PATH ), '/' );
    $relative = trim(str_replace($home_path, '', esc_url(add_query_arg(array()))), '/');
    $parts = explode( '/', $relative );
    if ( ! empty( $parts ) && ! isset( $parts[1] ) ) {
      return $parts[0];
    }
  }

}

该函数查看url之后的第一部分home_url(),如果与我们的现时匹配,则返回TRUE。此功能将用于检查我们的请求并执行所需的操作以显示我们的表单。

3:Custom_Reg\Form上课

现在,我将编写一个类,该类将负责生成表单标记。我还将使用它在属性中存储应用于显示表单的模板文件路径。

<?php 
// file: Form.php
namespace Custom_Reg;

class Form {

  protected $fields;

  protected $verb = 'POST';

  protected $template;

  protected $form;

  public function __construct() {
    $this->fields = new \ArrayIterator();
  }

  public function create() {
    do_action( 'custom_reg_form_create', $this );
    $form = $this->open();
    $it =  $this->getFields();
    $it->rewind();
    while( $it->valid() ) {
      $field = $it->current();
      if ( ! $field instanceof FieldInterface ) {
        throw new \DomainException( "Invalid field" );
      }
      $form .= $field->create() . PHP_EOL;
      $it->next();
    }
    do_action( 'custom_reg_form_after_fields', $this );
    $form .= $this->close();
    $this->form = $form;
    add_action( 'custom_registration_form', array( $this, 'output' ), 0 );
  }

  public function output() {
    unset( $GLOBALS['wp_filters']['custom_registration_form'] );
    if ( ! empty( $this->form ) ) {
      echo $this->form;
    }
  }

  public function getTemplate() {
    return $this->template;
  }

  public function setTemplate( $template ) {
    if ( ! is_string( $template ) ) {
      throw new \InvalidArgumentException( "Invalid template" );
    }
    $this->template = $template;
  }

  public function addField( FieldInterface $field ) {
    $hook = 'custom_reg_form_create';
    if ( did_action( $hook ) && current_filter() !== $hook ) {
      throw new \BadMethodCallException( "Add fields before {$hook} is fired" );
    }
    $this->getFields()->append( $field );
  }

  public function getFields() {
    return $this->fields;
  }

  public function getVerb() {
    return $this->verb;
  }

  public function setVerb( $verb ) {
    if ( ! is_string( $verb) ) {
     throw new \InvalidArgumentException( "Invalid verb" );
    }
    $verb = strtoupper($verb);
    if ( in_array($verb, array( 'GET', 'POST' ) ) ) $this->verb = $verb;
  }

  protected function open() {
    $out = sprintf( '<form id="custom_reg_form" method="%s">', $this->verb ) . PHP_EOL;
    $nonce = '<input type="hidden" name="_n" value="%s" />';
    $out .= sprintf( $nonce,  wp_create_nonce( 'custom_reg_form_nonce' ) ) . PHP_EOL;
    $identity = '<input type="hidden" name="custom_reg_form" value="%s" />';
    $out .= sprintf( $identity,  __CLASS__ ) . PHP_EOL;
    return $out;
  }

  protected function close() {
    $submit =  __('Register', 'custom_reg_form');
    $out = sprintf( '<input type="submit" value="%s" />', $submit );
    $out .= '</form>';
    return $out;
  }

}

该类生成表单标记,循环所有添加的字段,并create在每个字段上调用方法。每个字段都必须是的实例Custom_Reg\FieldInterface。添加了一个额外的隐藏字段以进行随机数验证。表单方法默认情况下为“ POST”,但可以使用setVerb方法将其设置为“ GET” 。创建完标记后,将标记保存在$formoutput()方法回显的对象属性内,并钩入'custom_registration_form'钩子:在表单模板中,只需调用即可do_action( 'custom_registration_form' )输出表单。

4:默认模板

就像我说的那样,可以很容易地覆盖表单模板,但是我们需要一个基本模板作为后备。我将在此处编写一个非常粗糙的模板,更多的是概念验证,而不是真实的模板。

<?php
// file: default_form_template.php
get_header();

global $custom_reg_form_done, $custom_reg_form_error;

if ( isset( $custom_reg_form_done ) && $custom_reg_form_done ) {
  echo '<p class="success">';
  _e(
    'Thank you, your registration was submitted, check your email.',
    'custom_reg_form'
  );
  echo '</p>';
} else {
  if ( $custom_reg_form_error ) {
    echo '<p class="error">' . $custom_reg_form_error  . '</p>';
  }
  do_action( 'custom_registration_form' );
}

get_footer();

5:Custom_Reg\FieldInterface界面

每个字段都应该是一个实现以下接口的对象

<?php 
// file: FieldInterface.php
namespace Custom_Reg;

interface FieldInterface {

  /**
   * Return the field id, used to name the request value and for the 'name' param of
   * html input field
   */
  public function getId();

  /**
   * Return the filter constant that must be used with
   * filter_input so get the value from request
   */
  public function getFilter();

  /**
   * Return true if the used value passed as argument should be accepted, false if not
   */
  public function isValid( $value = NULL );

  /**
   * Return true if field is required, false if not
   */
  public function isRequired();

  /**
   * Return the field input markup. The 'name' param must be output 
   * according to getId()
   */
  public function create( $value = '');
}

我认为这些注释解释了实现此接口的类应该做什么。

6:添加一些字段

现在我们需要一些字段。我们可以创建一个名为“ fields.php”的文件,在其中定义字段类:

<?php
// file: fields.php
namespace Custom_Reg;

abstract class BaseField implements FieldInterface {

  protected function getType() {
    return isset( $this->type ) ? $this->type : 'text';
  }

  protected function getClass() {
    $type = $this->getType();
    if ( ! empty($type) ) return "{$type}-field";
  }

  public function getFilter() {
    return FILTER_SANITIZE_STRING;
  }

  public function isRequired() {
    return isset( $this->required ) ? $this->required : FALSE;
  }

  public function isValid( $value = NULL ) {
    if ( $this->isRequired() ) {
      return $value != '';
    }
    return TRUE;
  }

  public function create( $value = '' ) {
    $label = '<p><label>' . $this->getLabel() . '</label>';
    $format = '<input type="%s" name="%s" value="%s" class="%s"%s /></p>';
    $required = $this->isRequired() ? ' required' : '';
    return $label . sprintf(
      $format,
      $this->getType(), $this->getId(), $value, $this->getClass(), $required
    );
  }

  abstract function getLabel();
}


class FullName extends BaseField {

  protected $required = TRUE;

  public function getID() {
    return 'fullname';
  }

  public function getLabel() {
    return __( 'Full Name', 'custom_reg_form' );
  }

}

class Login extends BaseField {

  protected $required = TRUE;

  public function getID() {
    return 'login';
  }

  public function getLabel() {
    return __( 'Username', 'custom_reg_form' );
  }
}

class Email extends BaseField {

  protected $type = 'email';

  public function getID() {
    return 'email';
  }

  public function getLabel() {
    return __( 'Email', 'custom_reg_form' );
  }

  public function isValid( $value = NULL ) {
    return ! empty( $value ) && filter_var( $value, FILTER_VALIDATE_EMAIL );
  }
}

class Country extends BaseField {

  protected $required = FALSE;

  public function getID() {
    return 'country';
  }

  public function getLabel() {
    return __( 'Country', 'custom_reg_form' );
  }
}

我已经使用一个基类来定义默认的接口实现,但是,可以添加非常自定义的字段来直接实现该接口,或者扩展基类并覆盖某些方法。

至此,我们已经拥有了显示表单的所有内容,现在我们需要进行验证和保存字段。

7:Custom_Reg\Saver上课

<?php
// file: Saver.php
namespace Custom_Reg;

class Saver {

  protected $fields;

  protected $user = array( 'user_login' => NULL, 'user_email' => NULL );

  protected $meta = array();

  protected $error;

  public function setFields( \ArrayIterator $fields ) {
    $this->fields = $fields;
  }

  /**
  * validate all the fields
  */
  public function validate() {
    // if registration is not allowed return false
    if ( ! get_option('users_can_register') ) return FALSE;
    // if no fields are setted return FALSE
    if ( ! $this->getFields() instanceof \ArrayIterator ) return FALSE;
    // first check nonce
    $nonce = $this->getValue( '_n' );
    if ( $nonce !== wp_create_nonce( 'custom_reg_form_nonce' ) ) return FALSE;
    // then check all fields
    $it =  $this->getFields();
    while( $it->valid() ) {
      $field = $it->current();
      $key = $field->getID();
      if ( ! $field instanceof FieldInterface ) {
        throw new \DomainException( "Invalid field" );
      }
      $value = $this->getValue( $key, $field->getFilter() );
      if ( $field->isRequired() && empty($value) ) {
        $this->error = sprintf( __('%s is required', 'custom_reg_form' ), $key );
        return FALSE;
      }
      if ( ! $field->isValid( $value ) ) {
        $this->error = sprintf( __('%s is not valid', 'custom_reg_form' ), $key );
        return FALSE;
      }
      if ( in_array( "user_{$key}", array_keys($this->user) ) ) {
        $this->user["user_{$key}"] = $value;
      } else {
        $this->meta[$key] = $value;
      }
      $it->next();
    }
    return TRUE;
  }

  /**
  * Save the user using core register_new_user that handle username and email check
  * and also sending email to new user
  * in addition save all other custom data in user meta
  *
  * @see register_new_user()
  */
  public function save() {
    // if registration is not allowed return false
    if ( ! get_option('users_can_register') ) return FALSE;
    // check mandatory fields
    if ( ! isset($this->user['user_login']) || ! isset($this->user['user_email']) ) {
      return false;
    }
    $user = register_new_user( $this->user['user_login'], $this->user['user_email'] );
    if ( is_numeric($user) ) {
      if ( ! update_user_meta( $user, 'custom_data', $this->meta ) ) {
        wp_delete_user($user);
        return FALSE;
      }
      return TRUE;
    } elseif ( is_wp_error( $user ) ) {
      $this->error = $user->get_error_message();
    }
    return FALSE;
  }

  public function getValue( $var, $filter = FILTER_SANITIZE_STRING ) {
    if ( ! is_string($var) ) {
      throw new \InvalidArgumentException( "Invalid value" );
    }
    $method = strtoupper( filter_input( INPUT_SERVER, 'REQUEST_METHOD' ) );
    $type = $method === 'GET' ? INPUT_GET : INPUT_POST;
    $val = filter_input( $type, $var, $filter );
    return $val;
  }

  public function getFields() {
    return $this->fields;
  }

  public function getErrorMessage() {
    return $this->error;
  }

}

该类有2种主要方法,一种(validate)循环字段,验证它们并将好的数据保存到数组中,另一种(save)将所有数据保存在数据库中并通过电子邮件将密码发送给新用户。

8:使用定义的类:完成Custom_Reg该类

现在,我们可以再次在Custom_Reg类上工作,添加“粘合”定义的对象并使它们起作用的方法

<?php 
// file Custom_Reg.php
namespace Custom_Reg;

class Custom_Reg {

  protected $form;

  protected $saver;

  function __construct( Form $form, Saver $saver ) {
    $this->form = $form;
    $this->saver = $saver;
  }

  /**
   * Check if the url to recognize is the one for the registration form page
   */
  function checkUrl() {
    $url_part = $this->getUrl();
    $nonce = urlencode( wp_create_nonce( 'registration_url' ) );
    if ( ( $url_part === $nonce ) ) {
      // do nothing if registration is not allowed or user logged
      if ( is_user_logged_in() || ! get_option('users_can_register') ) {
        wp_safe_redirect( home_url() );
        exit();
      }
      return TRUE;
    }
  }

  /**
   * Init the form, if submitted validate and save, if not just display it
   */
  function init() {
    if ( $this->checkUrl() !== TRUE ) return;
    do_action( 'custom_reg_form_init', $this->form );
    if ( $this->isSubmitted() ) {
      $this->save();
    }
    // don't need to create form if already saved
    if ( ! isset( $custom_reg_form_done ) || ! $custom_reg_form_done ) {
      $this->form->create();
    }
    load_template( $this->getTemplate() );
    exit();
  }

  protected function save() {
    global $custom_reg_form_error;
    $this->saver->setFields( $this->form->getFields() );
    if ( $this->saver->validate() === TRUE ) { // validate?
      if ( $this->saver->save() ) { // saved?
        global $custom_reg_form_done;
        $custom_reg_form_done = TRUE;
      } else { // saving error
        $err =  $this->saver->getErrorMessage(); 
        $custom_reg_form_error = $err ? : __( 'Error on save.', 'custom_reg_form' );
      }
    } else { // validation error
       $custom_reg_form_error = $this->saver->getErrorMessage();
    }
  }

  protected function isSubmitted() {
    $type = $this->form->getVerb() === 'GET' ? INPUT_GET : INPUT_POST;
    $sub = filter_input( $type, 'custom_reg_form', FILTER_SANITIZE_STRING );
    return ( ! empty( $sub ) && $sub === get_class( $this->form ) );
  }

  protected function getTemplate() {
    $base = $this->form->getTemplate() ? : FALSE;
    $template = FALSE;
    $default = dirname( __FILE__ ) . '/default_form_template.php';
    if ( ! empty( $base ) ) {
      $template = locate_template( $base );
    }
    return $template ? : $default;
  }

   protected function getUrl() {
    $home_path = trim( parse_url( home_url(), PHP_URL_PATH ), '/' );
    $relative = trim( str_replace( $home_path, '', add_query_arg( array() ) ), '/' );
    $parts = explode( '/', $relative );
    if ( ! empty( $parts ) && ! isset( $parts[1] ) ) {
      return $parts[0];
    }
  }

}

该类的构造函数接受的实例Form和的一个Saver

init()方法(使用checkUrl())查看之后的url的第一部分home_url(),如果它与正确的现时匹配,则检查是否已提交表单;如果使用Saver,则验证并保存用户数据,否则只需打印表单。

init()该方法还触发将'custom_reg_form_init'表单实例作为参数传递的动作挂钩:此挂钩应用于添加字段,设置自定义模板以及自定义form方法。

9:放在一起

现在我们需要编写主插件文件,在这里我们可以

  • 需要所有文件
  • 加载文本域
  • 使用实例化Custom_Reg类并init()使用合理的早期钩子对其调用方法来启动整个过程
  • 使用“ custom_reg_form_init”将字段添加到表单类

所以:

<?php 
/**
 * Plugin Name: Custom Registration Form
 * Description: Just a rough plugin example to answer a WPSE question
 * Plugin URI: https://wordpress.stackexchange.com/questions/10309/
 * Author: G. M.
 * Author URI: https://wordpress.stackexchange.com/users/35541/g-m
 *
 */

if ( is_admin() ) return; // this plugin is all about frontend

load_plugin_textdomain(
  'custom_reg_form',
  FALSE,
  plugin_dir_path( __FILE__ ) . 'langs'
); 

require_once plugin_dir_path( __FILE__ ) . 'FieldInterface.php';
require_once plugin_dir_path( __FILE__ ) . 'fields.php';
require_once plugin_dir_path( __FILE__ ) . 'Form.php';
require_once plugin_dir_path( __FILE__ ) . 'Saver.php';
require_once plugin_dir_path( __FILE__ ) . 'CustomReg.php';

/**
* Generate dynamic registration url
*/
function custom_registration_url() {
  $nonce = urlencode( wp_create_nonce( 'registration_url' ) );
  return home_url( $nonce );
}

/**
* Generate dynamic registration link
*/
function custom_registration_link() {
  $format = '<a href="%s">%s</a>';
  printf(
    $format,
    custom_registration_url(), __( 'Register', 'custom_reg_form' )
  );
}

/**
* Setup, show and save the form
*/
add_action( 'wp_loaded', function() {
  try {
    $form = new Custom_Reg\Form;
    $saver = new Custom_Reg\Saver;
    $custom_reg = new Custom_Reg\Custom_Reg( $form, $saver );
    $custom_reg->init();
  } catch ( Exception $e ) {
    if ( defined('WP_DEBUG') && WP_DEBUG ) {
      $msg = 'Exception on  ' . __FUNCTION__;
      $msg .= ', Type: ' . get_class( $e ) . ', Message: ';
      $msg .= $e->getMessage() ? : 'Unknown error';
      error_log( $msg );
    }
    wp_safe_redirect( home_url() );
  }
}, 0 );

/**
* Add fields to form
*/
add_action( 'custom_reg_form_init', function( $form ) {
  $classes = array(
    'Custom_Reg\FullName',
    'Custom_Reg\Login',
    'Custom_Reg\Email',
    'Custom_Reg\Country'
  );
  foreach ( $classes as $class ) {
    $form->addField( new $class );
  }
}, 1 );

10:缺少任务

现在一切都完成了。我们只需要自定义模板,可以在主题中添加自定义模板文件。

我们可以通过这种方式仅将特定样式和脚本添加到自定义注册页面

add_action( 'wp_enqueue_scripts', function() {
  // if not on custom registration form do nothing
  if ( did_action('custom_reg_form_init') ) {
    wp_enqueue_style( ... );
    wp_enqueue_script( ... );
  }
});

使用该方法,我们可以排队一些js脚本来处理客户端验证,例如this。编辑Custom_Reg\BaseField该类可以轻松处理使脚本起作用所需的标记。

如果要自定义注册电子邮件,可以使用标准方法并将自定义数据保存在meta上,我们可以在电子邮件中使用它们。

我们可能要执行的最后一项任务是阻止请求默认注册表单,就像这样简单:

add_action( 'login_form_register', function() { exit(); } );

所有文件都可以在这里找到。


1
哇,这是注册功能的完整重新设计!如果您想完全覆盖内置的注册过程,那可能是一个很好的解决方案。我认为不使用内置的注册表格不是一个好主意,因为您将失去其他核心功能,例如丢失的密码表格。然后,新注册的用户将需要显示传统的后端登录表单才能登录。
Fabien Quatravaux 2014年

1
@FabienQuatravaux丢失密码和登录表单只能像往常一样(后端)使用。是的,代码不完整,因为未处理丢失的密码和登录表单,但是OP问题仅与注册表单有关,答案已经太久了,无法添加其他功能...
gmazzap

13

TLDR;将以下形式放入主题,nameand id属性很重要:

<form action="<?php echo site_url('wp-login.php?action=register', 'login_post') ?>" method="post">
    <input type="text" name="user_login" value="Username" id="user_login" class="input" />
    <input type="text" name="user_email" value="E-Mail" id="user_email" class="input"  />
    <?php do_action('register_form'); ?>
    <input type="submit" value="Register" id="register" />
</form>

我找到了一篇出色的Tutsplus文章,内容涉及从头开始制作精美的Wordpress注册表格。这花了很多时间在样式表单上,但是在所需的wordpress代码中有以下相当简单的部分:

步骤4. WordPress

这里没有幻想。我们只需要隐藏在wp-login.php文件中的两个WordPress代码段即可。

第一个片段:

<?php echo site_url('wp-login.php?action=register', 'login_post') ?>  

和:

<?php do_action('register_form'); ?>

编辑:我从文章中添加了额外的最后一部分,以说明将上述代码片段放置在何处-它只是一种形式,因此它可以放入任何页面模板或侧边栏中,或从中制作一个简码。重要部分是,form其中包含上述代码段和重要的必填字段。

最终代码应如下所示:

<div style="display:none"> <!-- Registration -->
        <div id="register-form">
        <div class="title">
            <h1>Register your Account</h1>
            <span>Sign Up with us and Enjoy!</span>
        </div>
            <form action="<?php echo site_url('wp-login.php?action=register', 'login_post') ?>" method="post">
            <input type="text" name="user_login" value="Username" id="user_login" class="input" />
            <input type="text" name="user_email" value="E-Mail" id="user_email" class="input"  />
                <?php do_action('register_form'); ?>
                <input type="submit" value="Register" id="register" />
            <hr />
            <p class="statement">A password will be e-mailed to you.</p>


            </form>
        </div>
</div><!-- /Registration -->

请注意,在文本输入中具有和属性是非常重要且必要的;电子邮件输入也是如此。否则,它将无法正常工作。user_loginnameid

至此,我们完成了!


很好的解决方案!简单高效。但是,您将这些摘要放在哪里?在边栏中?该技巧仅适用于ajax注册表。
Fabien Quatravaux 2014年

1
感谢@FabienQuatravaux,我已经更新了答案,以包括本文的最后一部分。不需要AJAX表单-只需将POST表单提交到该wp-login.php?action=register页面即可
icc97 2014年


4

不久前,我创建了一个网站,该网站的前端显示了自定义注册表格。该网站不再可用,但是这里有一些屏幕截图。 登录表格 报名表格 密码遗失表格

这是我遵循的步骤:

1)通过“设置”>“常规”>“成员资格”选项激活所有访客请求新帐户的可能性。现在,注册页面显示在URL /wp-login.php?action=register上

2)自定义注册表格,使其看起来像您的网站前端。这比较棘手,取决于您使用的主题。

这是一个二十三个例子:

// include theme scripts and styles on the login/registration page
add_action('login_enqueue_scripts', 'twentythirteen_scripts_styles');

// remove admin style on the login/registration page
add_filter( 'style_loader_tag', 'user16975_remove_admin_css', 10, 2);
function user16975_remove_admin_css($tag, $handle){
    if ( did_action('login_init')
    && ($handle == 'wp-admin' || $handle == 'buttons' || $handle == 'colors-fresh'))
        return "";

    else return $tag;
}

// display front-end header and footer on the login/registration page
add_action('login_footer', 'user16975_integrate_login');
function user16975_integrate_login(){
    ?><div id="page" class="hfeed site">
        <header id="masthead" class="site-header" role="banner">
            <a class="home-link" href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home">
                <h1 class="site-title"><?php bloginfo( 'name' ); ?></h1>
                <h2 class="site-description"><?php bloginfo( 'description' ); ?></h2>
            </a>

            <div id="navbar" class="navbar">
                <nav id="site-navigation" class="navigation main-navigation" role="navigation">
                    <h3 class="menu-toggle"><?php _e( 'Menu', 'twentythirteen' ); ?></h3>
                    <a class="screen-reader-text skip-link" href="#content" title="<?php esc_attr_e( 'Skip to content', 'twentythirteen' ); ?>"><?php _e( 'Skip to content', 'twentythirteen' ); ?></a>
                    <?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'nav-menu' ) ); ?>
                    <?php get_search_form(); ?>
                </nav><!-- #site-navigation -->
            </div><!-- #navbar -->
        </header><!-- #masthead -->

        <div id="main" class="site-main">
    <?php get_footer(); ?>
    <script>
        // move the login form into the page main content area
        jQuery('#main').append(jQuery('#login'));
    </script>
    <?php
}

然后,修改主题样式表,以使表单按需要显示。

3)您可以通过调整显示的消息来进一步修改表单:

add_filter('login_message', 'user16975_login_message');
function user16975_login_message($message){
    if(strpos($message, 'register') !== false){
        $message = 'custom register message';
    } else {
        $message = 'custom login message';
    }
    return $message;
}

add_action('login_form', 'user16975_login_message2');
function user16975_login_message2(){
    echo 'another custom login message';
}

add_action('register_form', 'user16975_tweak_form');
function user16975_tweak_form(){
    echo 'another custom register message';
}

4)如果您需要前端注册表格,则可能不希望已注册用户登录时看到后端。

add_filter('user_has_cap', 'user16975_refine_role', 10, 3);
function user16975_refine_role($allcaps, $cap, $args){
    global $pagenow;

    $user = wp_get_current_user();
    if($user->ID != 0 && $user->roles[0] == 'subscriber' && is_admin()){
        // deny access to WP backend
        $allcaps['read'] = false;
    }

    return $allcaps;
}

add_action('admin_page_access_denied', 'user16975_redirect_dashbord');
function user16975_redirect_dashbord(){
    wp_redirect(home_url());
    die();
}

有很多步骤,但是结果就在这里!


0

更简单:使用WordPress功能wp_login_form()此处Codex页面)。

您可以制作自己的插件,以便可以在页面中使用简码:

<?php
/*
Plugin Name: WP Login Form Shortcode
Description: Use <code>[wp_login_form]</code> to show WordPress' login form.
Version: 1.0
Author: WP-Buddy
Author URI: http://wp-buddy.com
License: GPLv2 or later
*/

add_action( 'init', 'wplfsc_add_shortcodes' );

function wplfsc_add_shortcodes() {
    add_shortcode( 'wp_login_form', 'wplfsc_shortcode' );
}

function wplfsc_shortcode( $atts, $content, $name ) {

$atts = shortcode_atts( array(
        'redirect'       => site_url( $_SERVER['REQUEST_URI'] ),
        'form_id'        => 'loginform',
        'label_username' => __( 'Username' ),
        'label_password' => __( 'Password' ),
        'label_remember' => __( 'Remember Me' ),
        'label_log_in'   => __( 'Log In' ),
        'id_username'    => 'user_login',
        'id_password'    => 'user_pass',
        'id_remember'    => 'rememberme',
        'id_submit'      => 'wp-submit',
        'remember'       => false,
        'value_username' => NULL,
        'value_remember' => false
), $atts, $name );

// echo is always false
$atts['echo'] = false;

// make real boolean values
$atts['remember']       = filter_var( $atts['remember'], FILTER_VALIDATE_BOOLEAN );
$atts['value_remember'] = filter_var( $atts['value_remember'], FILTER_VALIDATE_BOOLEAN );

return '<div class="cct-login-form">' . wp_login_form( $atts ) . '</div>';

}

您要做的就是在前端上设置表单样式。


-1

如果您愿意使用插件,那么我之前已经使用过Gravity Forms的User Registration插件,它的效果很好:

http://www.gravityforms.com/add-ons/user-registration/

编辑:我知道这不是一个非常详细的解决方案,但它确实可以满足您的需求,并且是一个很好的解决方案。

编辑:为进一步扩展我的答案,重力表单的用户注册附加组件使您可以将使用重力表单创建的表单中的任何字段映射到用户特定的字段。例如,您可以使用名字,姓氏,电子邮件,网站,密码创建表单。提交后,加载项会将这些输入映射到相关的用户字段。

另一个很棒的事情是,您可以将任何注册用户添加到批准队列中。他们的用户帐户只有在管理员在后端批准后才能创建。

如果以上链接中断,则只有Google“为重力表格添加用户注册”


2
您是否在问题上加了@kaiser注释(大胆的我的名字
gmazzap

我有,但是我觉得该插件仍然值得一提,因为OP没有提到需要自定义代码。如果您认为有必要,很高兴将其移至评论
James Kemp 2014年

我不是国防部,所以我无法对您的回答发表评论。我只能投反对票,但我不能拒绝,因为我认为您的链接包含有用的信息,但是,仅链接的答案就没有用,即使该链接可以轻松更改,因此您的答案也变成了404。尝试在此处报告相关代码并解释该代码的作用,那么我想您的答案很好。
gmazzap

詹姆斯,我将赏金授予了包含代码的真实答案。如果您想要额外的赏金,请把插件拆开,然后向我们确切显示它在做什么。谢谢。
kaiser 2014年

嗨,Kaiser,我没被赏金,只是想分享我对插件的了解!
詹姆斯·肯普
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.