WordPress在开发插件的时候获取到当前登录用户

开发了很多插件,在获取当前登录用户时,总是需要使用add_action将代码往后挂钩,以使用wordpress的一些函数。但是开发到一个插件,不能往后挂钩、还要获取到当前登录用户的ID。

一般在插件中获取当前登录用户ID,有三种办法:

一、使用add_action将代码延后执行

在大多数情况下,如果业务代码可以延后执行也没问题,那么,你可以使用add_action将代码延后执行,这在网上大部分都是这么教你的。代码如下:

add_action("init",function(){
  //业务代码
  $userid = get_current_user_id();
});

二、使用api调用前台使用,比如rest api、wp ajax。

通过jq 的ajax去调用接口,获得当前登录用户,在使用rest api、wp ajax的同时也就可以使用get_current_user_id函数了,和方法一类似。这里不太常用,就不讲了。

三、根据cookie判断

根据Cookie判断这里我看了wordpress的源码,改写了一个程序,可以直接调用,代码如下:

<?php
function kekc_get_user_by( $field, $value ) {
	$userdata = WP_User::get_data_by( $field, $value );

	if ( ! $userdata ) {
		return false;
	}

	$user = new WP_User();
	$user->init( $userdata );

	return $user;
}

function kekc_wp_hash( $data, $scheme = 'auth' ) {
	$salt = kekc_wp_salt( $scheme );

	return hash_hmac( 'md5', $data, $salt );
}


function kekc_wp_salt( $scheme = 'auth' ) {
	static $cached_salts = array();
	if ( isset( $cached_salts[ $scheme ] ) ) {
		return $cached_salts[ $scheme ];
	}

	static $duplicated_keys;
	if ( null === $duplicated_keys ) {
		$duplicated_keys = array(
			'put your unique phrase here' => true,
		);

		/*
		 * translators: This string should only be translated if wp-config-sample.php is localized.
		 * You can check the localized release package or
		 * https://i18n.svn.wordpress.org/<locale code>/branches/<wp version>/dist/wp-config-sample.php
		 */
		$duplicated_keys[ __( 'put your unique phrase here' ) ] = true;

		foreach ( array( 'AUTH', 'SECURE_AUTH', 'LOGGED_IN', 'NONCE', 'SECRET' ) as $first ) {
			foreach ( array( 'KEY', 'SALT' ) as $second ) {
				if ( ! defined( "{$first}_{$second}" ) ) {
					continue;
				}
				$value                     = constant( "{$first}_{$second}" );
				$duplicated_keys[ $value ] = isset( $duplicated_keys[ $value ] );
			}
		}
	}

	$values = array(
		'key'  => '',
		'salt' => '',
	);
	if ( defined( 'SECRET_KEY' ) && SECRET_KEY && empty( $duplicated_keys[ SECRET_KEY ] ) ) {
		$values['key'] = SECRET_KEY;
	}
	if ( 'auth' === $scheme && defined( 'SECRET_SALT' ) && SECRET_SALT && empty( $duplicated_keys[ SECRET_SALT ] ) ) {
		$values['salt'] = SECRET_SALT;
	}

	if ( in_array( $scheme, array( 'auth', 'secure_auth', 'logged_in', 'nonce' ), true ) ) {
		foreach ( array( 'key', 'salt' ) as $type ) {
			$const = strtoupper( "{$scheme}_{$type}" );
			if ( defined( $const ) && constant( $const ) && empty( $duplicated_keys[ constant( $const ) ] ) ) {
				$values[ $type ] = constant( $const );
			} elseif ( ! $values[ $type ] ) {
				$values[ $type ] = get_site_option( "{$scheme}_{$type}" );
				if ( ! $values[ $type ] ) {
					$values[ $type ] = wp_generate_password( 64, true, true );
					update_site_option( "{$scheme}_{$type}", $values[ $type ] );
				}
			}
		}
	} else {
		if ( ! $values['key'] ) {
			$values['key'] = get_site_option( 'secret_key' );
			if ( ! $values['key'] ) {
				$values['key'] = wp_generate_password( 64, true, true );
				update_site_option( 'secret_key', $values['key'] );
			}
		}
		$values['salt'] = hash_hmac( 'md5', $scheme, $values['key'] );
	}

	$cached_salts[ $scheme ] = $values['key'] . $values['salt'];

	/** This filter is documented in wp-includes/pluggable.php */
	return $cached_salts[ $scheme ];
}


function kekc_parse_auth_cookie( $cookie = '', $scheme = '' ) {
	if ( empty( $cookie ) ) {
		switch ( $scheme ) {
			case 'auth':
				$cookie_name = AUTH_COOKIE;
				break;
			case 'secure_auth':
				$cookie_name = SECURE_AUTH_COOKIE;
				break;
			case 'logged_in':
				$cookie_name = LOGGED_IN_COOKIE;
				break;
			default:
				if ( is_ssl() ) {
					$cookie_name = SECURE_AUTH_COOKIE;
					$scheme      = 'secure_auth';
				} else {
					$cookie_name = AUTH_COOKIE;
					$scheme      = 'auth';
				}
		}
		if ( empty( $_COOKIE[ $cookie_name ] ) ) {
			return false;
		}
		$cookie = $_COOKIE[ $cookie_name ];
	}

	$cookie_elements = explode( '|', $cookie );
	if ( count( $cookie_elements ) !== 4 ) {
		return false;
	}

	list( $username, $expiration, $token, $hmac ) = $cookie_elements;

	return compact( 'username', 'expiration', 'token', 'hmac', 'scheme' );
}

function kekc_validate_auth_cookie( $cookie = '', $scheme = '' ) {
	$cookie_elements = kekc_parse_auth_cookie( $cookie, $scheme );
	if ( ! $cookie_elements ) {
		return false;
	}

	$scheme     = $cookie_elements['scheme'];
	$username   = $cookie_elements['username'];
	$hmac       = $cookie_elements['hmac'];
	$token      = $cookie_elements['token'];
	$expired    = $cookie_elements['expiration'];
	$expiration = $cookie_elements['expiration'];

	// Allow a grace period for POST and Ajax requests.
	if ( wp_doing_ajax() || 'POST' === $_SERVER['REQUEST_METHOD'] ) {
		$expired += HOUR_IN_SECONDS;
	}

	// Quick check to see if an honest cookie has expired.
	if ( $expired < time() ) {
		return false;
	}

	$user = kekc_get_user_by( 'login', $username );
	if ( ! $user ) {
		return false;
	}

	$pass_frag = substr( $user->user_pass, 8, 4 );

	$key = kekc_wp_hash( $username . '|' . $pass_frag . '|' . $expiration . '|' . $token, $scheme );

	// If ext/hash is not present, compat.php's hash_hmac() does not support sha256.
	$algo = function_exists( 'hash' ) ? 'sha256' : 'sha1';
	$hash = hash_hmac( $algo, $username . '|' . $expiration . '|' . $token, $key );

	if ( ! hash_equals( $hash, $hmac ) ) {
		return false;
	}

	$manager = WP_Session_Tokens::get_instance( $user->ID );
	if ( ! $manager->verify( $token ) ) {
		return false;
	}

	// Ajax/POST grace period set above.
	if ( $expiration < time() ) {
		$GLOBALS['login_grace_period'] = 1;
	}

	return $user->ID;
}

function kekc_get_current_user_id() {
    $cookie_elements = kekc_validate_auth_cookie($_COOKIE[ LOGGED_IN_COOKIE ],'logged_in');
    return $cookie_elements;
}

使用方法:

$current_user_id = kekc_get_current_user_id();//当前登录ID
$current_user = kekc_get_user_by("id",$current_user_id);//当前登录用户信息
© 版权声明
THE END
喜欢就支持一下吧
点赞5 分享
评论 抢沙发
头像
欢迎您留下宝贵的见解!
提交
头像

昵称

取消
昵称常用语 夸夸
夸夸
还有吗!没看够!
表情代码图片

    暂无评论内容