繁体   English   中英

Wordpress - 如何使用 php 获取设备类型和上次登录位置

[英]Wordpress - How to get device type and last login location with php

我写了这个 function 允许用户查看上次登录的日期(不是当前登录)。 现在我还想显示登录的位置和设备。 我试图搜索但找不到解决我问题的方法。 任何人都可以对此有所了解吗? 我感谢任何帮助。

// Function that set last login
add_action('wp_login', 'set_last_login', 0, 2);
function set_last_login($login, $user) {
  $user = get_user_by('login',$login);
  $time = current_time( 'timestamp' );
  $last_login = get_user_meta( $user->ID, '_last_login', 'true' );
  if(!$last_login) {
    update_user_meta( $user->ID, '_last_login', $time );
  } 
   else {
    update_user_meta( $user->ID, '_last_login_prev', $last_login );
    update_user_meta( $user->ID, '_last_login', $time );
  }
}

// Function that get last login
function get_last_login($user_id, $prev = null) {
  $last_login = get_user_meta($user_id);
  $time = current_time( 'timestamp' );
  if(isset($last_login['_last_login_prev'][0]) && $prev) {
  $last_login = get_user_meta($user_id, '_last_login_prev', 'true' );
  } 
  else if(isset($last_login['_last_login'][0])) {
    $last_login = get_user_meta($user_id, '_last_login', 'true' );
  } 
  else {
    update_user_meta( $user_id, '_last_login', $time );
    $last_login = $last_login['_last_login'][0];
  } return $last_login;
}

试图得到这样的东西在此处输入图像描述

检测位置:

您可能需要考虑使用HTML5 Geolocoation API

否则,IP 可能会告诉您一些关于位置的信息: How to get Real IP from Visitor?

位置检测的其他选项包括:

地理定位器-PHP

谷歌地理编码 API

最大思维 (php)

检测设备:

https://github.com/serbanghita/Mobile-Detect/

https://www.codexworld.com/mobile-device-detection-in-php/

http://mobiledetect.net/

一些上下文,位置是基于浏览器(至少在桌面上)的“接受共享”,这意味着在浏览器提示后,您(用户)需要接受共享您的位置。

您应该能够通过Location Web API获得 javascript 的经纬度,然后从Nominatim OpenStreetMap API获得地址。

然后我们可以将所有内容传递给 PHP 到 ajax,并将其存储为用户元数据。


基本示例

以下内容尚未准备就绪。 这是一个有效的概念证明。

检索用户位置

首先,要使用Ajax我们需要jQuery 我们还需要将 Ajax url 传递给我们的脚本才能处理请求。 出于安全原因,我们还需要传递Nonce 这是通过wp_localize_script() function 完成的。

<?php

/**
 * Enqueue jquery.
 *
 * @see https://releases.jquery.com/
 */
wp_enqueue_script( 'jquery-min', 'https://code.jquery.com/jquery-3.6.1.min.js', array(), '3.6.1', true );

//Add jquery integrity key
add_filter( 'script_loader_tag', function ( $tag, $handle, $src ) {

    if ( 'jquery-min' === $handle ) {

        $tag = str_replace(
            "></script>",
            " integrity='sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=' crossorigin='anonymous'></script>",
            $tag
        );

    };

    return $tag;

}, 10, 3 );

//Enqueue my-script
wp_enqueue_script( 'my-script', trailingslashit( get_template_directory_uri() ) . 'assets/js/my-script.js', array( 'jquery-min' ), wp_get_theme()->version, true );

/**
 * Pass the ajax admin url and a freshly generated nonce to our script.
 *
 * Apparently we should now use wp_add_inline_script instead of wp_localize_script to expose a global object that needs to be used by your script.
 * @see Jules Colle comment in the User Contributed Notes section.
 * @see https://developer.wordpress.org/reference/functions/wp_add_inline_script/#user-contributed-notes
 */
wp_localize_script( 'my-script', 'localize', array(
    '_ajax_url' => admin_url( 'admin-ajax.php' ),
    '_ajax_nonce' => wp_create_nonce( '_ajax_nonce' ),
) );

之前说过,我们可以使用免费的Nominatim OpenStreetMap API (目前2022年底),根据经纬度反推位置,并将结果发送到我们的后端进行处理。

if ( navigator.geolocation ) {
    
    /**
     * Use the browser Geolocation API.
     * Prompt the user to share his location.
     * 
     * @see https://developer.mozilla.org/en-US/docs/Web/API/Geolocation_API
     */
    window.navigator.geolocation.getCurrentPosition( function( position ) {

        let lat = position.coords.latitude;
        let lon = position.coords.longitude;

        /**
         * Reverse geocoding.
         * 
         * @https://nominatim.org/release-docs/latest/api/Reverse/
         */
        $.getJSON(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${ lat }&lon=${ lon }`, function( object ) {
            
            let adress = object.address;
            
            //Send the ajax request.
            $.ajax( {
                type: 'POST',
                url: localize._ajax_url,
                data: {
                    _ajax_nonce: localize._ajax_nonce,
                    action: '_wpso_73934145',
                    openStreetMapObject: adress,
                },
                success: function ( response ) {
                    console.log( response.data );
                },
            } );
        } );
    } );
};

我们的 javascript ajax 请求需要由我们的 PHP 操作 function 来回答,这将触发我们的update_user_meta() function。

<?php

add_action( 'wp_ajax__wpso_73934145', function () {

    if ( check_ajax_referer( '_ajax_nonce' ) ) {

        $user_id = get_current_user_id();
  
        $openStreetMapObject = $_POST['openStreetMapObject'];

        $meta_key = '_user_position';

        $meta_value = array(
            'openStreetMapObject' => $openStreetMapObject,
        );

        update_user_meta( $user_id, $meta_key, $meta_value );

        wp_send_json_success( $meta_value );

    } else {

        wp_send_json_error();

    };

    wp_die();

} );

在前端,我们可以通过get_user_meta()访问我们的元数据。

<?php

$user_id = get_current_user_id();

$meta_key = '_user_position';

if ( metadata_exists( 'user', $user_id, $meta_key ) ) {

    $meta_value = get_user_meta( $user_id, $meta_key, true);

    var_dump( $meta_value );

    var_dump( $meta_value['openStreetMapObject']['city_district'] );

} else {
    
    echo 'You need to share your location';

};

检索用户设备

关于设备,我们可以检索用户代理。 要解密用户代理并了解它的含义,我建议阅读Mozzila 用户代理开发人员文档指南

<?php

add_action( 'init', function () {

    if ( is_user_logged_in() ) {

        $user_agent = $_SERVER['HTTP_USER_AGENT'];

        var_dump( $user_agent );

    };

} );

备择方案

反向搜索用户 IP,这样我们就可以在不提示用户的情况下检索用户的大致位置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM