在信息时代,数据安全和隐私保护变得越来越重要,所以我们会需要各种方式来保护自己的不想被未经授权而被阅读的文章内容。这次分享的是一个通过代码隐藏和加密,将部分文章内容保护起来的代码。
代码
1.在主题的functions.php文件添加以下代码:
function encrypted_content_shortcode($atts, $content = null) {
extract(shortcode_atts(array('key' => ''), $atts));
if (isset($_POST['e_secret_key']) && $_POST['e_secret_key'] === $key) {
// 如果输入的密码正确,则显示解锁的内容
return '<div class="unlocked-content">' . $content . '</div>';
} else {
// 如果密码不正确或未输入密码,则显示密码输入表单和错误提示
$error_message = '';
if (isset($_POST['e_secret_key'])) {
$error_message = '<p class="error-message">密码错误,请重新输入。</p>';
}
return '<style>
.error-message {
color: red;
}
.content-password-form {
display: flex;
flex-direction: column;
align-items: center;
}
.password-input {
padding: 10px;
margin-bottom: 10px;
border: 1px solid #ccc;
border-radius: 4px;
}
.unlock-button {
padding: 10px 20px;
background-color: #4CAF50;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.content-reminder {
color: red;
margin-bottom: 10px;
}
</style>
<form method="post" class="content-password-form">
<p class="content-reminder">此内容需密码解锁查看,请先获取密码!</p>
<input type="password" name="e_secret_key" placeholder="请输入密码" class="password-input" />
<input type="submit" value="解锁" class="unlock-button" />
' . $error_message . '
</form>';
}
}
add_shortcode('encrypted', 'encrypted_content_shortcode');
2.在编辑文章的时候使用短码包围要隐藏的内容,如:
[encrypted key="123456"] 这里是要隐藏和加密的内容。 [/encrypted]
其中 123456 是需要设置的密码。
效果如图:
