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 ‘<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’ );

});

});

© 版权声明
THE END
喜欢就支持一下吧
点赞0
分享
评论 抢沙发

请登录后发表评论