WordPress文章密码保护Ajax设置
以下代码由PHP站长网 52php.cn收集自互联网现在PHP站长网小编把它分享给大家,仅供参考 wordpress 中对于文章有一个密码访问的功能,后台发布文章时填写密码即可设置。在 WordPress 中 Ajax 的应用越来越多,要做到密码文章查看无刷新应用,请看下面的代码: add_action('wp_ajax_do_post_password','do_x_post_password_cb'); add_action('wp_ajax_nopriv_do_post_password','do_x_post_password_cb'); function do_x_post_password_cb() { require_once( ABSPATH . 'wp-includes/class-phpass.php' ); $wp_hasher = new PasswordHash(8,true); // 10 天 setcookie( 'wp-postpass_' . COOKIEHASH,$wp_hasher->HashPassword( stripslashes( $_POST['pass'] ) ),time() + 864000,COOKIEPATH ); ? $_COOKIE['wp-postpass_' . COOKIEHASH] = $wp_hasher->HashPassword( stripslashes( $_POST['pass'] ) ); $q = new WP_Query( "p={$_POST['pid']}" ); if ( $q->have_posts() ) : while( $q->have_posts() ) : $q->the_post(); $error = false; if ( post_password_required() ) { $error = true; } ob_start(); echo '<a href="'; the_permalink(); echo '">'; the_title(); echo '</a>'; $title = ob_get_clean(); @ob_end_flush(); ob_start(); the_content(); $content = ob_get_clean(); @ob_end_flush(); endwhile; endif; wp_reset_postdata(); $return = array( 'title' => $title,'content' => $content,'error' => '' ); if ($error) $return['error'] = '密码不正确'; die( json_encode( $return ) ); } 实现功能所必须的 php,加载到你的 functions.php 中。这里设置了 10 天的 cookie,输入正确密码后 10 天内不需要再次输入,可根据你自己的需要更改。 jQuery(document).ready( function($) { $('.post-password-required').on( 'submit','form[action$="postpass"]',function( ev ) { ev.preventDefault(); var id = $(this).find('label').attr('for').replace('pwbox-',''), ajaxurl = barley.ajaxurl, loading = ''; $(this).find('input[type="submit"]').css({ 'background-image': 'url('+loading+')', 'background-position': '92% 50%', 'background-repeat': 'no-repeat', 'padding-right': '25px' }).attr('disabled','disabled'); $.post( ajaxurl,{ action: 'do_post_password', pass: $(this).find('input[name="post_password"]').val(), pid: id },function( response ) { if ( response.error != '' ) { response.content = '<p class="error" background:#fcc;padding:10px;">'+ response.error+'</p>' + response.content; } else { $('#post-'+id).find('.posttitle').html( response.title ); } $('#post-'+id).find('.postcontent').html( response.content ); },'json' ); }); }); 以上内容由PHP站长网【52php.cn】收集整理供大家参考研究如果以上内容对您有帮助,欢迎收藏、点赞、推荐、分享。 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |