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" style="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' );
	});
});

js需注意posttitle与postcontent这两个class类,注意ajaxurl的路径。

会员用户如有疑问可咨询我,我将为你详细解答

至此,教程结束