last day (15 days later) » 

12:11 PM
1
A: Wordpress - How to get device type and last login location with php

amarinediaryYou should be able to get the location through javascript through the Location Web API and pass the value through ajax to php and the save it as a metadata. To use ajax we need to pass it to our script, we will be also passing a nonce: <?php wp_enqueue_script( 'my-ajax-script', trailingslashit( ...

 
Thanks for your answer, I think it can work. But I have a doubt about the device and the user agent. If I use the function as you wrote it should show the device of the currently logged in user, but that's not what I need to do. I need to capture the device used at login moment and view it later. Just like with the date and with the geolocation example you wrote.
 
The user agent is the current device. If you want to learn more about user agents here is the mozilla documentation: developer.mozilla.org/en-US/docs/Web/HTTP/Headers/User-Agent
 
Excuse my ignorance, I'm trying to use your advice but I don't understand where to put certain things. I created my-ajax-script and put the js geolocation code. Then enqueue script, localize script and ad_action I put them in functions.php. But all of this is not working. Am I doing something wrong ? Also, how can I view the location on screen?
 
I assumed you had a bit of experienced with php and javascript. We're setting a user metadata which will store our latitude and longitude if the user accept to share it (ONLY, can't be bypassed). If you wish to retrieve the metadata you can use get_user_meta(). I will update the answer. For a better understanding of Ajax you should read AJAX in Plugins.
To be able to use ajax you also need jQuery, which you should enqueue if that's not the case yet.
 
Thanks, I appreciate your help. The last thing, I have everything in child-theme, so I should use get_stylesheet_directory_uri(); instead of get_template_directory_uri() right?
 
12:11 PM
hey
 
Hello
 
Will be easier there
 
Sure =)
 
I don't have your current folder architecture so whatever works tbh.
You could add console.log( 'my-script.js has been successfully loaded' ); at the top of your js file and look at the console.
 
OK, my path is / wp-content / themes / child-theme / woocommerce / myaccount here I have all the files I'm working on, templates, assets, etc ..
 
12:14 PM
get_template_directory_uri should work I think
 
Now I try, let's see how it goes.
 
Sure, I will stay logged in untill it works for you
 
Is it a problem for you if I write you step by step what I do?
Thank you so much for your kindness. I appreciate it.
 
No go ahead I have time.
No worries
 
Ok, Step 1. I created my-ajax-script.js and put inside assets folder. Path: /wp-content/themes/child-theme/woocommerce/myaccount/assets/my-ajax-script.js
Inside my-ajax-script.js:
if ( navigator.geolocation ) {
window.navigator.geolocation.getCurrentPosition( function( position ) {
$.ajax( {
type: 'POST',
url: localize._ajax_url,
data: {
_ajax_nonce: localize._ajax_nonce,
action: '_wpso_73934145',
latitude: position.coords.latitude,
longitude: position.coords.longitude,
},
success: function ( response ) {
console.log( response.data );
},
} );
} );
};
 
12:21 PM
Good so far
 
Step 2. I take this code and I put it in my child theme's functions.php, right ?
wp_enqueue_script( 'my-ajax-script', trailingslashit( get_template_directory_uri() ) . 'assets/js/my-ajax-script.js', array(), wp_get_theme()->version, true );

wp_localize_script( 'my-ajax-script', 'localize', array(
'_ajax_url' => admin_url( 'admin-ajax.php' ),
'_ajax_nonce' => wp_create_nonce( '_ajax_nonce' ),
) );
 
Are you also enqueuing jQuery before ?
Try to understand the whole concept beside just copy/pasting.
Ajax needs jQuery to run.
 
No I'm not queuing, how can I do this?
 
To be able to use ajax in our javascript file we need to pass it's url to our script
```
<?php

//enqueue jquery
wp_enqueue_script( 'jquery-min', 'https://code.jquery.com/jquery-3.6.1.min.js', array(), '3.6.1', true );
```
```
<?php

//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 );
```
```
<?php

//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 );
```
 
Oh, this is something I've never done. Excuse me.
 
12:28 PM
```
<?php

//pass ajax and a nonce to my-script
wp_localize_script( 'my-script', 'localize', array(
'_ajax_url' => admin_url( 'admin-ajax.php' ),
'_ajax_nonce' => wp_create_nonce( '_ajax_nonce' ),
) );
```
@Snorlax No problem, I was just saying that it is better for you to actually understand what you're doing instead of just copy pasting.
Documentation is boring tho in WordPress it is pretty necessary to always read it
 
Right, understanding the concept is key as I will be able to handle any future errors or changes.
 
Exactly
 
Ok, so I understand that we need to give the url of the js file to our script, right?
 
yes
For ajax to be able to send request tou our server, it needs to be referenced first
The nonce is a security measure, preventing empty requests
(I've updated the first part of the answer to include jQuery, it should be easier to read)
 
I understand. So now the first thing I need to do in functions.php is to append jquery as you showed.

//enqueue jquery
wp_enqueue_script( 'jquery-min', ' code.jquery.com/… ', array(), '3.6.1', true );
 
12:36 PM
yeah pretty much, it should look like the first part of the updated answer stackoverflow.com/a/73935713/3645650
 
Ok, I achieved this by modifying the parts that correspond with my folder structure. I noticed the change in the first part of the answer and I went back step by step to try to understand how it works.
What is jquery integrity key?
 
Was gonna talk about that
Script that depends on CDNs (content delivery network) usually needs an integrity key.
 
I understand, so it's a security measure.
 
yeah, but for them
You just need it to use it
 
clear
 
12:48 PM
If you click on any version a popup will be shown with the tag and the integrity key
 
I understand now
 
The proper way to include a script in WordPress is by using wp_enqueue_script.
The only way to had the integrity key is by intercepting the tag before it's render and modifying it. (that's what add_filter( 'script_loader_tag', ... and str_replace( ... do.
 
that's just what we've done now.
 
Yeah, only (aha)
"We load the tools to be able to do the thing"
 
The last doubt I have is about get_template_directory_uri (), I'm not sure it's correct, so I write console.log ('my-script.js has been successfully loaded'); to see if the path is correct?
 
12:54 PM
I've never used child theme, as I always build the project from scratch
115
A: get_template_directory_uri pointing to parent theme not child theme

Tim Maloneget_template_directory_uri() will always return the URI of the current parent theme. To get the child theme URI instead, you need to use get_stylesheet_directory_uri(). You can find these in the documentation, along with a list of other useful functions for getting various theme directory locat...

Apparently you can't use it in a child theme
So indeed you were right, get_stylesheet_directory_uri() should be used instead
In a child theme context
 
Yes, I had read a little bit about this, so I had a doubt. So now I try like this. get_stylesheet_directory_uri() ) . 'woocommerce/myaccount/assets/my-script.js'
 
Yeah.
The console.log() trick is just to let you know if the script is actually loading. It's easier to know like that.
 
Ok, now the final step
<?php

add_action( 'wp_ajax__wpso_73934145', function () {

if ( check_ajax_referer( '_ajax_nonce' ) ) {

$user_id = get_current_user_id();

$latitude = $_POST['latitude'];

$longitude = $_POST['longitude'];

$meta_key = '_user_position';

$meta_value = array(
'latitude' => $latitude,
'longitude ' => $longitude,
);

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

wp_send_json_success( $meta_value );

} else {

wp_send_json_error();

};

wp_die();

} );
Does this go into functions.php after the code we just wrote?
 
Yes it does.
So wp_ajax_{action}.
the {action} part is actually referenced in the javascript function.
```
$.ajax( {
type: 'POST',
url: localize._ajax_url,
data: {
_ajax_nonce: localize._ajax_nonce,
action: '_wpso_73934145',
//...
```
This _wpso_73934145 can be whatever you want.
 
ah, ok, now it's clear to me.
 
1:01 PM
But if you change it then you need to update the modular part of the backend function.
the {action}
@Snorlax Great!
 
$user_id = get_current_user_id();

$meta_value = get_user_meta( $user_id, '_user_position', true);

echo $meta_value;
Now to show the information I put this in my template.php?
 
yeah on the front end
We're retrieving the meta from the user's metadatas
The user should get a prompte from the browser (Tested on chrome), if he accept, the lat/lng is sent as an ajax request which fire the update_user_meta in the backend
prompt*
 
OK, nothing happens for now. I did var_dump ($ meta_valu); and I get NULL
 
Did you get the browser prompt
to share location
 
Sorry my bad
string(0) ""
 
1:10 PM
uhm
 
i did var_dump ($ meta_valu); instead of var_dump ($ meta_value);
No, I have not received the browser prompt
 
Which browser are you using ?
All browser are supported by the location API so that's not it
 
Chrome last version
 
Found a mistake
Jquery url should be https://code.jquery.com/jquery-3.6.1.min.js
I left the placeholder from my snippets
Everything is working on my end
 
Yes, I had already corrected this.
 
1:17 PM
No space between $ dollar sign and meta_value
var_dump( $meta_value );
 
Yes, right, I had corrected that too
//enqueue jquery
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_stylesheet_directory_uri() ) . 'woocommerce/myaccount/assets/my-script.js', array( 'jquery-mi
This is the entire code in functions.php
if ( navigator.geolocation ) {
window.navigator.geolocation.getCurrentPosition( function( position ) {
$.ajax( {
type: 'POST',
url: localize._ajax_url,
data: {
_ajax_nonce: localize._ajax_nonce,
action: '_wpso_73934145',
latitude: position.coords.latitude,
longitude: position.coords.longitude,
},
success: function ( response ) {
console.log( response.data );
},
} );
} );
};

in my-ajax-js
and in my template.php <?php
$user_id = get_current_user_id();

$meta_value = get_user_meta( $user_id, '_user_position', true);

var_dump( $meta_value );
echo $meta_value;
?>
 
Can you open the console and look if any error are showing up on refresh ?
 
I was watching right now, mo I have no mistake ..
 
Is the script loading ?
my-script ?
Have you verified the name, the handle ? the location ?
Remove echo $meta_value;;
 
OK, after page refresh i get this error, GET mywebsite/wp-content/themes/astra-child/woocommerce/myaccount/… net::ERR_ABORTED 404
 
1:31 PM
Just keep the var_dump
Are you logged-in on your website ?
 
yes
 
Can you console log the following from your js file : console.log( 'localize._ajax_nonce' );
And refresh
And tell me if you get a string
 
Yep, now i try
Wait, I understand what the problem is. I changed the name of the js file from my-ajax-script to my-script. I received the browser prompt on geolocation and I accepted.
So it worked now.
 
Yeah !
Great !
 
my-script.js has been successfully loaded
it's correct
 
1:37 PM
Are you getting the location then ?
 
There is a final problem. With var_dump I get lat, long, etc .. but with echo I get arrays.
[user_login_history] array(2) { ["latitude"]=> string(10) "40.7601152" ["longitude "]=> string(10) "14.4375808" } Array
 
yeah that's normal data is stored under an array
 
Ok, again excuse my ignorance. I have the last questions to ask.
 
echo $meta_value['latitude']; ... etc
 
you just answered the first question xD
 
1:40 PM
```
<?php

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

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

echo $meta_value['latitude'];

echo $meta_value['longitude'];

} else {

echo 'You need to share your location';

};
```
 
The problem is that I would like to print the location name and not latitude and longitude
I am trying to build something similar.
 
The geolocation API is browser based and only let you retrieve lat/lng.
You would then take that data and root it through for example the Google Map Reverse Geolocation API
Any service that does that is usually "pay per request"
Meaning it's not free
 
I understand. So from this point on, do you think it is more appropriate to rely on a plugin?
 
I'm the wrong person to ask, I hate plugins.
Tbh most of them make you pay for something that would take half a day to code.
5
Q: PHP Latitude Longitude to Address

Joe TorracaI have a form on my website where a user enters an address of a place. When they submit the form, I convert this location into latitude/longitude and store this in a MySQL Database. I am using Google's Geocode service for this conversion. The problem is that I can't find either a class or a servi...

You can refer to this tho i'm pretty sure this is outdated
As Google went from a free API to a Pay one $
 
I hate plugins too. For this I am trying to build my website from scratch and without relying on any plugin.
 
1:50 PM
So plugins can be good if you make them yourself specifically for your website. But generic/popular ones are just bad
 
Ok, I think you really helped me a lot. I infinitely appreciate the time you have dedicated to me. Can I have your contact? In this way, if I have a job or a project I would like to hire you to make it happen.
 
Sure, that's not my main job tho =D
 
All right. I will try to look at the last reference you gave me to understand if I can do it, otherwise I will consider the paid google map geolocation.
 
Glad I was able to help !
 
<3
 
Last question
 
Open street Map is the free open Api you might be able to do smothing with it
 
Eventually I would dedicate myself to complete the function with a paid google api map. My doubt is: do I necessarily have to have the browser request about the location? Can't I retrieve the information without the browser request?
 
That's the downside of Europe
RGPD, private info and all
 
bullshit xD
 
2:02 PM
Ahah
You can prevent the use of the website if they don't share the location
Depending on your service, you might have enough persuasion
By the way, this seems to be working
 
I understand the legal issues. Anyway this login date and location thing was to provide an extra security option for my website users. But I can also think about not introducing it as there are many other things to deal with.
 
Using Open street map to reverse the geolocation
If you're worrying about account sharing I have a solution for that
 
From which country do you write me if I can know?
 
France
 
I had guessed you were Italian for some reason, I am from Italy anyway.
What are you referring to ? "If you're worrying about account sharing I have a solution for that"
 
2:08 PM
From the name ? Yeah, just my origins !
 
Yep! =)
 
Like for example I have a sas that services Pilot trainee, helping them with the exam, an MCQ website. I don't want them to share accounts.
Be cause I would loose money.
So, I'm limiting user sessions, and pinging the backend to use if the user is still online regularly
... to see if ... *
saas*
 
I understand. I don't know if it can actually be useful to me. My website deals with fitness topics, so I'm going to publish scientific articles on physical activity and health.

The only service I will offer for a fee is the sale of personalized training programs. So from this point of view the sharing of accounts does not worry me as I will work directly with the customer 1 to 1
Are there any other cases where it might be useful to avoid account sharing?
 
No pretty much it. It's just the same problem as Netflix, Prime and all the other SaaS that sell subscription products or products behind a pay wall.
 
2:23 PM
I understand. Then I thank you again, you have been really thorough and kind. You helped me understand something new and I am grateful for that.

Have a nice day.
 
One sec
 
Ye
 
Trying to get you the city from Open Street
 
Ah OK. Then I'm still waiting here.
 
2:48 PM
Yeah so that's working
 
Good
Was it difficult ?
 
Kinda
Tried in php couldn't for some reason
Js was way easier
 
Do you want me to start doing something with my js file?
 
One sec cleaning up stuff
 
Yeah
 
3:06 PM
```
if ( navigator.geolocation ) {
window.navigator.geolocation.getCurrentPosition( function( position ) {
let lat = position.coords.latitude;
let lon = position.coords.longitude;
$.getJSON(`https://nominatim.openstreetmap.org/reverse?format=json&lat=${lat}&lon=${lon}`, function( object ) {
let adress = object.address;
$.ajax( {
type: 'POST',
url: localize._ajax_url,
data: {
_ajax_nonce: localize._ajax_nonce,
action: '_wpso_73934145',
latitude: lat,
longitude: lon,
openStreetMapObject: adress,
},
```
<?php

add_action( 'wp_ajax__wpso_73934145', function () {

if ( check_ajax_referer( '_ajax_nonce' ) ) {

$user_id = get_current_user_id();

$latitude = $_POST['latitude'];

$longitude = $_POST['longitude'];

$longitude = $_POST['longitude'];

$openStreetMapObject = $_POST['openStreetMapObject'];

$meta_key = '_user_position';

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

update_user_meta( $user_id, $meta_key, $meta_value );
==========================
==========================
So this is working, it will pass the open street map adress as a object and store it in our user metadata.
 
Uh, thanks again. Now I try. But before moving on. With the Js code you posted, do I need to replace it with the one I already have?
 
Yeah jsut call it my-script-2 or something don't erase the previous one just in case you need to go back to it
Tbh that whole script is probably not production ready, it's more a proof of concept than anything else
Like performance wised there is probably a better approach ... etc
==============================
==============================
```
<?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['openStreetMapObject']['city_district'] );

} else {

echo 'You need to share your location';

};
```
==============================
==============================
You pretty much need to modify the js file and the php response
 
i see two times longitude, it's an error ?
$longitude = $_POST['longitude'];

$longitude = $_POST['longitude'];
 
typo
remove one
 
yep
 
3:18 PM
i'm a bit tired =p
 
But I would say that it is also normal, you have dedicated yourself a lot to this. More than I would have done myself =)
I'll try with your latest suggestions and see what I get.
again infinitely thank you.
 
Tbh it's a pretty cool question
No worries I had fun
 
I'll write you a message in the comments to let you know how it went.
 
sure
 
A greeting and good day.
 
3:22 PM
u2
 
3:39 PM
array(3) { ["latitude"]=> string(10) "40.7601152" ["longitude"]=> string(10) "14.4375808" ["openStreetMapObject"]=> NULL }
 
delete_user_meta( get_current_user_id(), '_user_position' );
The refresh the share position setting
and it should work
 
where put delete user meta for deleting user_position ?
 
function.php or template.php anywhere where it can be triggered
just to reset the meta as the previous value didn't had the OpenStreetMapObject in it
 
Ok, done..
now im getting You need to share your location
 
Then remove it then share the location
Then remove the deleta_user_meta ...
 
3:48 PM
I reset the permissions, after refresh the prompt asked me for location permission and I accepted it, but it still displays this.
 
Have you removed the delete_user_meta ?
 
yes
 
It's working on my end
 
I'll try again
 
I have updated the answer stackoverflow.com/a/73935713/3645650
Which might be more understandable. because SO chat app is awful to share code
 
3:57 PM
Reloaded everything is working great. Fantastic!!!
 
Amazing !
 
Can I somehow pass the browser request? I know it is illegal in europe but i am curious to understand how it works without request, i would like to try it.
 
So Actually that might just be on desktop
It might work directly on mobile
Would need to check
Because on mobile you're sharing with the app (the browser) straight away
You might be able to do something with the IP
Each IP adress is specific to a country so you can at least get that
 
I understand, okay, so now I really have to go. Thanks again for all the help. Greetings.
 
See ya
 
4:02 PM
;P
 

last day (15 days later) »