我的问题很简单。我正在从事一个将WordPress用作无头CMS(类似)的项目。我创建了一个ajax端点,但它总是返回400。现在,我创建了一个子主题来测试这些功能。下面是函数。我正在使用的php。
<?php
function login_with_ajax()
{
echo "hey"; exit();
$username = $_POST[\'username\'];
$password = $_POST[\'password\'];
if (!$username) {
echo json_encode(
array(
\'status\' => false,
\'message\' => \'Username is required\'
)
);
exit();
}
if (!$password) {
echo json_encode(
array(
\'status\' => false,
\'message\' => \'Password is required\'
)
);
exit();
}
$creds = array();
$creds[\'user_login\'] = $username;
$creds[\'user_password\'] = $password;
$creds[\'remember\'] = true;
$user = wp_signon($creds, false);
$userID = $user->ID;
wp_set_current_user($userID, $username);
wp_set_auth_cookie($userID, true, false);
do_action(\'wp_login\', $username);
if ( is_user_logged_in() ) {
echo json_encode(
array(
\'status\' => true,
)
);
} else {
echo json_encode(
array(
\'status\' => false,
\'message\' => \'Invalid login credentials\'
)
);
}
}
add_action("wp_ajax_nopriv_login_ajax", "login_with_ajax");
我正在尝试使用这样的fetch访问它。fetch(\'/wp-admin/admin-ajax.php\', {
method: \'POST\',
headers: { \'content-type\': \'application/json\' },
body: JSON.stringify({ username: \'thewhitefang\', password: \'@bhishek01\', action: \'login_ajax\' }),
})
我做错什么了吗?编辑:此端点将不会在WordPress中使用。