可以使用自定义帖子类型和自定义字段(ACF)进行登录吗


Can a login be made using custom post types and custom fields (ACF)?

是否可以使用WordPress自定义帖子类型和高级自定义字段创建登录系统?

我创建了一个名为"用户"的自定义帖子类型,其中我有这样的结构:

  • 职位名称
  • 用户电子邮件(使用ACF的文本类型字段)
  • 用户密码(使用ACF的密码类型字段)

有了这些帮助,我实际上自己注册用户,我想。

我的问题是数据库的结构,保存在哪里,因为我认为我不能从前面的登录表单登录用户

我尝试了一些查询,但有些问题似乎不对。有人能帮我做这个吗。我是否在正确的轨道上?

$login_email = $_POST['login_email'];
$login_password = $_POST['login_password'];
$email_sql = $wpdb->get_var($wpdb->prepare("SELECT meta_value FROM ".$wpdb->postmeta." WHERE meta_key = %s AND meta_value = %s",'user_email', $login_email));
$pass_sql = $wpdb->get_results($wpdb->prepare("SELECT meta_value FROM ".$wpdb->postmeta." WHERE meta_key = %s AND meta_value = %s",'user_password', $login_password));

问题是,用户电子邮件和用户密码都是元密钥,它们不是同一个记录,我想我不能基于此登录。我是对的还是有办法?

您可以在Wordpress中执行元查询来查询自定义字段。

$user = new WP_Query(array(
    'posts_per_page' => 1,
    'meta_query' => array(
        'relation' => 'and',
        array(
            'key' => 'username',
            'value' => $_POST['username'],
            'compare' => '='
        ),
        array(
            'key' => 'password',
            'value' => $_POST['password'],
            'compare' => '='
        )
    )
));

如果usernamepassword自定义字段与提供的值匹配,则以上内容将返回一个post。

注意:以上代码只是示例。您需要正确处理密码哈希,以保护您的代码等。

编辑:在与@Anonymous聊天后,发现事情有点复杂,但最终的解决方案是:

$login_email = $_POST['email'];
// Hash the plain text password.
$login_password = wp_hash_password($_POST['password']);
// Find a post with the ACF Custom value that matches our username.
$user_query = new WP_Query(array( 
    'posts_per_page' => 1, 
    'post_type' => 'users', 
    'meta_query' => array( 
        'relation' => 'or', 
        array( 
            'key' => 'email_user', 
            'value' => $login_email, 
            'compare' => '=' 
        ) 
    ) 
)); 
// Check if the user exists.
if ($user_query->have_posts()) { 
    while($user_query->have_posts()){
        // Load the current post.
        $user_query->the_post(); 
        // Get the current post.
        $user = get_post();
        // Get the hashed password from the post.
        $hashed_password = get_post_meta($user->ID, 'password', true); 
        // Compare the hashed passwords.
        if (wp_check_password(wp_hash_password($login_password), $hashed_password)) { 
            echo "logged in successfull"; 
        } else { 
            echo "user found, password incorrect"; 
        }
    }
}