当前位置:秋硕笔记 > 主机 > 正文

WordPress文章密码保护Ajax

WordPress文章密码保护Ajax
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 '';
the_title();
echo '
';
$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 = '

'+ response.error+'

' + response.content;
} else {
$('#post-'+id).find('.posttitle').html( response.title );
}
$('#post-'+id).find('.postcontent').html( response.content );
}, 'json' );
});
});

感觉很棒!可以赞赏支持我哟~

赞(0) 打赏

评论抢沙发