未经测试的伪代码示例,您可以扩展这些示例来解决这些问题:
function get_the_user_ip() {
if ( ! empty( $_SERVER[\'HTTP_CLIENT_IP\'] ) ) {
//check ip from share internet
$ip = $_SERVER[\'HTTP_CLIENT_IP\'];
} elseif ( ! empty( $_SERVER[\'HTTP_X_FORWARDED_FOR\'] ) ) {
// to check ip is pass from proxy
$ip = $_SERVER[\'HTTP_X_FORWARDED_FOR\'];
} else {
$ip = $_SERVER[\'REMOTE_ADDR\'];
}
return apply_filters( \'get_the_user_ip\', $ip );
}
然后,可以将所有数据存储在一个post\\u元字段中,只需正确构造数组即可。
array(
\'like\' => array(
\'ip1\', \'ip2\', \'ip3\', \'etc\'
),
\'dislike\' => array(
\'ip4\', \'ip5\', \'ip6\', \'etc\'
)
)
通过这种方式,您可以创建一些助手函数(或者最好是一个具有一些getter和setter方法的类),以便在加载UI和保存数据时引用。
function get_like_count( $type = \'like\' ) {
// get post meta ##
$array = get_post_meta( get_the_ID(), \'post_meta_field\' );
// @todo -- validate it is an array and the requested key exists ##
// return count ##
return count( $array[ $type ] );
}
function set_like_count( $type = \'like\' ) {
// get post meta ##
$array = get_post_meta( get_the_ID(), \'post_meta_field\' );
// @todo -- validate it is an array and the requested key exists ##
// update count for post ##
$array[ $type ][] = get_the_user_ip();
// save ##
update_post_meta( get_the_ID(), \'post_meta_field\', $array );
}
/** check if the user IP is already stored for this post */
function has_liked() {
// get post meta ##
$array = get_post_meta( get_the_ID(), \'post_meta_field\' );
// @todo -- validate it is an array and the requested key exists ##
// search the array for the IP value
// this might need to search each array key if you want to know what action the user took ##
return in_array( get_the_user_ip(), $array );
}