Answers:
当您将帖子设置为受密码保护时,该保护即发生在get_the_content()
功能上。WordPress会检查发布的密码cookie,如果未设置,则无效或已过期,然后显示密码表格。
将此密码表单提交到wp-login.php
,根据该表单中写入的密码设置一个cookie,然后将请求再次重定向到该帖子。
可以这样描述该过程:
我们可以做什么:
'the_password_form'
编辑表单的输出,添加电子邮件字段和带有帖子ID的隐藏字段(这时我们在get_the_content
函数内部,因此我们可以访问全局post变量)第一步:
/**
* Customize the form, adding a field for email and a hidden field with the post id
*/
add_filter( 'the_password_form', function( $output ) {
unset( $GLOBALS['the_password_form'] );
global $post;
$submit = '<input type="submit" name="Submit" value="' . esc_attr__('Submit') . '" /></p>';
$hidden = '<input type="hidden" name="email_res_postid" value="' . $post->ID . '">';
$email = '</p><p><label for="email_res">' . __( 'Email:' );
$email .= '<input name="email_res" id="email_res" type="text" size="20" /></label></p><p>';
return str_replace( $submit, $hidden . $email . $submit, $output );
}, 0 );
第二个:
/**
* Set the post password cookie expire time based on the email
*/
add_filter( 'post_password_expires', function( $valid ) {
$postid = filter_input( INPUT_POST, 'email_res_postid', FILTER_SANITIZE_NUMBER_INT );
$email = filter_input( INPUT_POST, 'email_res', FILTER_SANITIZE_STRING );
// a timestamp in the past
$expired = time() - 10 * DAY_IN_SECONDS;
if ( empty( $postid ) || ! is_numeric( $postid ) ) {
// empty or bad post id, return past timestamp
return $expired;
}
if ( empty($email) || ! filter_var($email, FILTER_VALIDATE_EMAIL) ) {
// empty or bad email id, return past timestamp
return $expired;
}
// get the allowed emails
$allowed = array_filter( (array)get_post_meta( $postid, 'allow_email' ), function( $e ) {
if ( filter_var( $e, FILTER_VALIDATE_EMAIL) ) return $e;
});
if ( ! empty( $allowed ) ) { // some emails are setted, let's check it
// if the emails posted is good return the original expire time
// otherwise return past timestamp
return in_array( $email, $allowed ) ? $valid : $expired;
}
// no emails are setted, return the original expire time
return $valid;
}, 0 );
我们完了。
现在创建一个帖子,另存为受密码保护,并使用键在自定义字段中设置一些允许的电子邮件'allow_email'
。您可以添加的电子邮件数量没有限制...