在提交密码时使用AJAX保护帖子内容并避免页面刷新

在提交密码时使用AJAX保护帖子内容并避免页面刷新,ajax,wordpress,password-protection,Ajax,Wordpress,Password Protection,这是给WordPress的,只是为了说明这一点。我在这里提问是因为我怀疑我需要在这个问题上提供悬赏(价值400英镑) 我需要在表单提交中添加AJAX,以避免页面重新加载/页面刷新。我试过几种不同的版本,但都不管用 这里的总体思路是保护文章的某些部分,其中的部分是用 add_filter( 'the_content', 'wrap_code_in_shortcode' , 9 ); function wrap_code_in_shortcode( $content ) { if ( !

这是给WordPress的,只是为了说明这一点。我在这里提问是因为我怀疑我需要在这个问题上提供悬赏(价值400英镑)

我需要在表单提交中添加AJAX,以避免页面重新加载/页面刷新。我试过几种不同的版本,但都不管用

这里的总体思路是保护文章的某些部分,其中的部分是用

add_filter( 'the_content', 'wrap_code_in_shortcode' , 9 );
function wrap_code_in_shortcode( $content ) {

    if ( ! in_category( 'premium' ) ) return $content;
    
    $content = preg_replace('/(<pre[^>]*>\s*<code[^>]*>)/',"[protected]$1", $content);

    $content = preg_replace('/(<\/code>\s*<\/pre>)/', "$1[/protected]", $content);

    return $content;
}

add_shortcode( 'protected', 'protected_function' );
function protected_function($atts, $content=null){

    $userpass = isset( $_REQUEST['password']) ? $_REQUEST['password'] : (isset($_COOKIE['userpass']) ? $_COOKIE['userpass'] : NULL );

        if ( in_array( $userpass, array('testpw') ) ) {

            $return_code = do_shortcode( $content );

        } else {

    $return_code = '<div style="margin-top:20px; font-size:15px">Submit password to view.</div>
    
    <div id="errorPWdata"></div>

        <form method="post" onsubmit="protectedFunction(this);">

            <input required style="display: block; width: 69%; height: 50px; margin-right: 1%; float: left; border: 2px solid #333;" type="text" placeholder="&#32;Password Here" name="password" id="userpass">

            <input style="display: block; margin: 0px; width: 30%; height: 50px; background-color: #333; color: #fff;" id="protectedButton" type="submit" value="Submit">

        </form>';
    
        ?>
    <script>

        function protectedFunction(form) {
        $('#protectedButton').on( 'click', function(e) {
        e.preventDefault();
        $.ajax({
                success: function(data) {
                    $("#errorPWdata").html(data);
                },
                error: function() {
                    alert("Password record error. Contact the administrator.");
                }
            });
        document.cookie = "userpass=" + escape(form.userpass.value) + "; path=/";
    }
}
    </script>
    <?php
}

    return $return_code;

}
这些标签有四个不同的类别

  • PHP
  • HTML
  • CSS
  • JS
这就是为什么
preg_replace
使用
('/(]*>\s*]*>)
格式,因为它需要覆盖(处理)添加的类

此外,设置cookie后,一旦用户提供了正确的密码,就可以记住密码。用户不必在每次查看包含受保护内容的帖子时都重新输入密码

我有一个空DIV作为显示消息(成功和错误)的占位符。这里的想法是在用户提交错误密码时显示错误。如果密码匹配,则显示内容(代码)

这是我正在研究的代码:

add_action( 'wp_ajax_get_protected_content', 'get_protected_content' );
add_action( 'wp_ajax_nopriv_get_protected_content', 'get_protected_content' );
function get_protected_content() {
    // validation
    if ( empty( $_POST['post_id'] ) ) {
        wp_send_json_error( 'Wrong Post ID' );
    }
    $post_id = (int)$_POST['post_id'];

    if ( empty( $_POST['password'] ) || ! is_user_password_valid( $_POST['password'], $post_id ) ) {
        wp_send_json_error( 'Wrong Password' );
    }
    
    $content = get_post_field( 'post_content', $post_id );
    // var_dump($content);
    if ( preg_match( '/(<pre[^>]*>\s*<code[^>]*>.*<\/code>\s*<\/pre>)/', $content, $matches ) ) {
        wp_send_json_success( apply_filters( 'the_content', $matches[1] ) );
    } else {
        wp_send_json_error( 'No Protected Content Found' );
    }
}
add_filter('the_content','wrap_code_in_shortcode',9);
函数在快捷码中换行代码($content){
如果(!in_category('premium')返回$content;
$content=preg_replace(“/(]*>\s*]*>)/”,“[protected]$1”,$content);
$content=preg_replace(“/(\s*)/”、“$1[/protected]”、$content);
返回$content;
}
添加_短代码('protected','protected_function');
函数保护函数($atts,$content=null){
$userpass=isset($_请求['password'])?$_请求['password']:(isset($_COOKIE['userpass'])?$_COOKIE['userpass']:NULL);
if(在数组($userpass,array('testpw'))中){
$return\u code=do\u短代码($content);
}否则{
$return_code='提交密码以查看。
';
?>
函数保护函数(形式){
$('protectedButton')。打开('click',函数(e){
e、 预防默认值();
$.ajax({
成功:功能(数据){
$(“#errorPWdata”).html(数据);
},
错误:函数(){
警报(“密码记录错误。请与管理员联系”);
}
});
document.cookie=“userpass=“+escape(form.userpass.value)+”路径=/”;
}
}

请尝试以下代码

短码处理部分:

add_shortcode( 'protected', 'shortcode_protected' );
//将[protected]短代码添加到内容中。
添加\u过滤器('the \u content','wrap \u code \u in \u shortcode',9);
函数在快捷码中换行代码($content){
如果(!in_category('premium')返回$content;
$content=preg_replace(“/(]*>\s*]*>)/”,“[protected]$1”,$content);
$content=preg_replace(“/(\s*)/”、“$1[/protected]”、$content);
返回$content;
}
//用于检查密码是否有效的函数
函数是用户密码有效($userpass,$post\u id){
返回数组($userpass,数组('test'));
}
//定义短代码。您可以将此节与换行代码(在短代码()中)组合(合并)
添加_短代码('protected','shortcode_protected');
函数短码受保护($atts,$content=null){
$userpass=isset($_请求['password'])?$_请求['password']:(isset($_COOKIE['userpass'])?$_COOKIE['userpass']:NULL);
$post_id=获取_id();
如果(用户密码有效($userpass,$post\u id)){
$return\u code=do\u短代码($content);
}否则{
$return\u代码=
'
提交密码以查看。
';
$return\u代码='
函数getProtectedContent(事件){
event.preventDefault();
让password=event.target.elements.password.value;
jQuery.ajax({
url:“'.admin_url('admin-ajax.php')”,
方法:“张贴”,
数据:{
操作:“获取受保护的内容”,
邮政编码:'.$post\U id',
密码
},
成功:功能(结果){
如果(结果、成功){
jQuery(“#保护区”).html(result.data);
document.cookie=“userpass=“+password+”;path=/”;
}否则{
警报(结果、数据);
}
},
错误:函数(){
警惕(“有什么不对劲了”);
}
});
返回false;
}
';
}
返回$return\u代码;
}
Ajax请求处理部分:

add_shortcode( 'protected', 'bio_protected_function' );
add_action('wp_ajax_get_protected_content','get_protected_content');
添加操作(“wp\u ajax\u nopriv\u获取受保护的内容”、“获取受保护的内容”);
函数获取受保护的内容(){
//验证
if(空($\u POST['POST\u id'])){
wp_send_json_错误('error Post ID');
}
$post_id=(int)$_post['post_id'];
if(空($_POST['password'])| |!用户密码有效($_POST['password'],$POST\u id)){
wp_发送_json_错误('错误密码');
}
$content=get\u post\u字段('post\u content',$post\u id);
//var_dump($content);
if(preg_match('/(]*>\s*]*>.*\s*)/',$content,$matches)){
wp_发送_json_成功(应用_过滤器('the_content',$matches[1]);
}否则{
wp_发送_json_错误(“未找到受保护的内容”);
}
}

希望这段代码对您有所帮助。

我学习了如何详细说明您的代码片段并注意错误。 请先把所有的东西都读一遍,然后你可以试试

错误1 使用错误的函数名定义了短代码

<script>
    function protectedFunction(form) {
        $('#protectedButton').on('click', function (e) {
            e.preventDefault();
            $.ajax({
                success: function (data) {
                    $("#errorPWdata").html(data);
                },
                error: function () {
                    alert("Password record error. Contact the administrator.");
                }
            });
            document.cookie = "userpass=" + escape(form.userpass.value) + "; path=/";
        }
    }
</script>
应替换为

add_action( 'wp_enqueue_scripts', function () {
    wp_enqueue_script(
        'bio-shortcode-protected',
        get_theme_file_uri( 'assets/js/bio-shortcode-protected.js' ),
        [ 'jquery' ],
        '1',
        true
    );
} );
wp_enqueue_scripts();
错误2 脚本标记sh
add_action( 'wp_enqueue_scripts', function () {
    wp_enqueue_script(
        'bio-shortcode-protected',
        get_theme_file_uri( 'assets/js/bio-shortcode-protected.js' ),
        [ 'jquery' ],
        '1',
        true
    );
} );
wp_enqueue_scripts();
jQuery(function($){
    const settings = window.bioShortcodeData;

    function init() {
        $('#protectedForm').on( 'submit', function(e) {
            e.preventDefault();

            const form = this;

            $.post({
                url: settings['endpoint'],
                data: {
                    'action': settings['action'],
                    'bio-post-id': settings['post-id'],
                    'nonce': settings['nonce'],
                    'password': form.userpass.value,
                },
                success: function(data) {
                    if (!data.status) {
                        alert(data.message);

                        $('#errorPWdata')
                            .empty()
                            .append(data.message);

                        return;
                    }

                    if (data.isValidPassword) {
                        document.cookie = "userpass=" + escape(form.userpass.value) + "; path=/";
                    }

                    $('#bio-protected-content').replaceWith(data.content);
                    init() // for reattach submission handler
                },
                error: function() {
                    alert("Server error");
                }
            });

        })
    }

    init();
})
function bio_protected_function( $atts, $content = null ) {
    add_action( 'wp_enqueue_scripts', function () {
        wp_enqueue_script(
            'bio-shortcode-protected',
            get_theme_file_uri( 'assets/js/bio-shortcode-protected.js' ),
            [ 'jquery' ],
            '1',
            true
        );
        wp_localize_script(
            'bio-shortcode-protected',
            'bioShortcodeData',
            [
                'post-id'  => get_the_ID(),
                'nonce'    => wp_create_nonce( 'bio-shortcode' ),
                'endpoint' => admin_url( 'admin-ajax.php' ),
                'action'   => 'bio_protected_code'
            ]
        );
    } );
    wp_enqueue_scripts();

    if ( bio_validate_the_password() ) {
        return do_shortcode( $content );
    }

    ob_start();
    ?>
    <div class="bio-protected-content" id="bio-protected-content">
        
        <div style="margin-top:20px; font-size:15px">Submit password to view.</div>

        <div id="errorPWdata"></div>

        <form method="post" id="protectedForm">

            <input required
                   style="display: block; width: 69%; height: 50px; margin-right: 1%; float: left; border: 2px solid #333;"
                   type="text" placeholder="&#32;Password Here" name="password" id="userpass">

            <input style="display: block; margin: 0px; width: 30%; height: 50px; background-color: #333; color: #fff;"
                   id="protectedButton" type="submit" value="Submit">

        </form>
    </div>
    <?php

    return ob_get_clean();
}
add_action( 'wp_ajax_nopriv_bio_protected_code', 'bio_protected_code_endpoint' );
add_action( 'wp_ajax_bio_protected_code', 'bio_protected_code_endpoint' );
function bio_protected_code_endpoint() {
    $is_valid_nonce = wp_verify_nonce( $_REQUEST['nonce'], 'bio-shortcode' );
    if ( ! $is_valid_nonce ) {
        wp_send_json(
            [
                'status'  => false,
                'message' => 'Invalid nonce',
            ]
        );
        exit;
    }

    $post_id = $_REQUEST['bio-post-id'];

    $post_type           = get_post_type( $post_id );
    $available_post_type = 'your-post-type';
    if ( $available_post_type !== $post_type ) {
        wp_send_json(
            [
                'status'  => false,
                'message' => 'Not available post type',
            ]
        );
        exit;
    }

    global $post;

    $post    = get_post( $post_id );
    $content = apply_filters( 'the_content', $post->post_content );

    wp_send_json(
        [
            'status'          => true,
            'isValidPassword' => bio_validate_the_password(),
            'content'         => $content
        ]
    );

    exit;
}
function bio_validate_the_password() {
    $userpass = $_REQUEST['password'] ?? $_COOKIE['userpass'] ?? null;

    return in_array( $userpass, [ 'testpw' ] );
}