这是我提出的解决方案,它依赖于数据库中已有的信息。
后台
每个受密码保护的帖子都将密码以明文形式存储在
wp_posts
表(在
post_password
列)。我们可以使用它来查询数据库中任何分配了该密码的帖子,并根据该密码获取帖子信息。从那里,我们可以重定向到受密码保护的帖子。
假设/约束
OP表示,客户将使用自定义登录表单输入其特殊密码。我假设表单已经创建,并且可以使用GET请求发送密码,因为它已经是纯文本。
OP还指出,保护帖子/页面的每个密码都是唯一的。我假设唯一密码是与此答案分开生成的。
它的工作原理client_key
发送(通过表单获取或通过链接)并使用get_query_var()
. 如果存在,请检查wp_posts
密码设置等于的第一篇帖子的表client_key
并将行作为对象返回。
健全性检查:如果已创建对象,请创建几个变量以在JavaScript函数中使用。
回声ascript
元素,该元素将运行POST函数wp-login.php
. 这模仿了首次访问受密码保护的页面时通常会发生的表单发布。在那里,客户端将被提示输入查看帖子内容的密码,一旦给了密码,就会创建一个cookie以允许将来访问内容。此函数在后台执行相同的表单提交,重定向到相应的帖子(基于GUID)。
最后,仅在以下情况下在站点前端运行该功能wp_head
被激发(当jQuery[通常]被加载时)。
代码
<?php
/**
* Add our custom query string to the global query_vars.
*
* @param array $vars The global vars used throughout WP.
*
* @return array
*/
function wpse134962_add_query_vars_filter( $vars ) {
$vars[] = \'client_key\';
return $vars;
}
add_filter( \'query_vars\', \'wpse134962_add_query_vars_filter\' );
/**
* Redirect to a password-protected page based on the query string.
*
* If client_key is passed in the query string, check the database for a post that
* has a password assigned that equals the client_key. If one is found, submit the
* login form to create the cookie that allows entry, then redirect to the post.
*/
function wpse134962_password_redirect() {
$client_key = get_query_var( \'client_key\' ) ? get_query_var( \'client_key\' ) : \'\';
if ( ! empty( $client_key ) ) {
/** @var wpdb $wpdb */
global $wpdb;
$query = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_password = %s", $client_key );
$password_posts = $wpdb->get_row( $query );
if ( isset( $password_posts ) ) {
$post_id = $password_posts->ID;
$login_url = site_url( \'wp-login.php\' );
echo <<<HTML
<script>
jQuery(function() {
var postURL = "$login_url?action=postpass",
postData = {
post_password: "$client_key"
},
postRedirect = function() {
document.location = "{$password_posts->guid}";
};
jQuery.post( postURL, postData, postRedirect() );
})();
</script>
HTML;
}
}
}
if ( ! is_admin() ) {
/** Only fire on the front end of the site. */
add_action( \'wp_head\', \'wpse134962_password_redirect\' );
}