Geocoding custom user meta in WordPress - wordpress

I'm using User Front End Pro to provide a front end registration form. One line of that is for an address, and I want to use that to display a map of all users with Geo Mashup.
I have a custom field that saves to user meta called geocode_address, I need to then geocode it and output it to two separate fields Latitude and Longitude. I found this for geocoding custom post data, and have tried to amend it for user meta, but it is not working, and causes the registration to hang. What have I done wrong?
function geocode_address($user_id)
{
$custom_fields = get_user_meta();
if(isset($custom_fields["geocode_address"]) && !empty($custom_fields["geocode_address"][0]))
{
$resp = wp_remote_get( "http://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($custom_fields["geocode_address"][0])."&sensor=false" );
if ( 200 == $resp['response']['code'] ) {
$body = $resp['body'];
$data = json_decode($body);
if($data->status=="OK"){
$latitude = $data->results[0]->geometry->location->lat;
$longitude = $data->results[0]->geometry->location->lng;
update_user_meta($user_id, "latitude", $latitude);
update_user_meta($user_id, "longitude", $longitude);
}
}
}
}
add_action('update_user_meta', 'geocode_address');
As a side note, Geomashup has a function to geocode a custom field, but when I enter "geocode address" it doesn't seem to work...

The action update_user_meta takes more arguments and the first one is not the User ID:
add_action('update_user_meta', 'geocode_address', 10, 4 );
function geocode_address( $meta_id, $user_id, $meta_key, $meta_value )
{
if( 'geocode_address' == $meta_key )
{
var_dump( $meta_value );
die();
}
}
Then, you're using get_user_meta() wrong, we need to pass at least the User ID: get_user_meta($user_id, $key = '', $single = false);. But I suspect it's not needed in your case.
As for the Geocode API, it returned a correct response when I tested with a random spanish address:
$address = "gran via, madrid";
$resp = wp_remote_get( "http://maps.googleapis.com/maps/api/geocode/json?address=".urlencode($address)."&sensor=false" );

Related

Pre fill Woocommerce Reset Password field with URL parameter

I am trying to send out emails to my customers and allow them one click to reset passwords with their email pre-filled on the reset password page by URL /account/lost-password/?email=123#gmail.com
However, I am not sure how to make it right. Here is my code. Thanks!
add_action( 'template_redirect', 'set_custom_data_wc_session' );
function set_custom_data_wc_session () {
if ( isset( $_GET['email'] ) ) {
$em = isset( $_GET['email'] ) ? esc_attr( $_GET['email'] ) : '';
// Set the session data
WC()->session->set( 'custom_data', array( 'email' => $em ) );
}
}
add_filter( 'woocommerce_login_form' , 'prefill_login_form' );
function prefill_login_form ( $fields ) {
// Get the session data
$data = WC()->session->get('custom_data');
// Email
if( isset($data['email']) && ! empty($data['email']) )
$fields['user_login']['default'] = $data['email'];
return $fields;
}
I managed to do it by referencing this thread
Pre-fill Woocommerce login fields with URL variables saved in session
<?php
add_action('woocommerce_lostpassword_form','woocommerce_js_2');
function woocommerce_js_2()
{ // break out of php
?>
<script>
// Setup a document ready to run on initial load
jQuery(document).ready(function($) {
//var r = /[?|&](\w+)=(\w+)+/g; //matches against a kv pair a=b
var r = /[?|&](\w+)=([\w.-]+#[\w.-]+)/g;
var query = r.exec(window.location.href); //gets the first query from the url
while (query != null) {
//index 0=whole match, index 1=first group(key) index 2=second group(value)
$("input[name="+ query[1] +"]").attr("value",query[2]);
query = r.exec(window.location.href); //repeats to get next capture
}
});
</script>
<?php } // break back into php

Auto redirection in WooCommerce after login based on user meta data

I am trying to check if a user meta data is empty or not. If empty, redirect the user to a page, else redirect to the default page.
But my following codes is only redirecting to the default page.
add_filter('woocommerce_login_redirect', 'ac_my_acct_login_redirect');
function ac_my_acct_login_redirect($redirect_to) {
$user_id = get_current_user_id();
$father = get_user_meta( $user_id, 'fath_name', true );
$update_pro = esc_url(get_permalink('123')); // the page I want for redirection if metadata is empty
$my_acct = esc_url(get_permalink( wc_get_page_id( 'myaccount' ) )); // default woocommerce my account page
if(empty($father)){
$redirect_to = $update_pro;
}
else {
$redirect_to = $my_acct;
}
return $redirect_to;
}
meta key = fath_name (even it has value, still the redirection is not working as intended). Any advice?
Your code contains some mistakes
get_current_user_id() is not necessary, as $user is passed to the callback function
get_permalink() expects an int (123), not a string ("123")
Make sure the page ID actually exists
So you get:
function filter_woocommerce_login_redirect( $redirect, $user ) {
// Get user meta
$value = get_user_meta( $user->ID, 'fath_name', true );
// Empty
if ( empty( $value ) ) {
$redirect = get_permalink( 123 );
} else {
// Get the "My account" url
$redirect = get_permalink( wc_get_page_id( 'myaccount' ) );
}
return $redirect;
}
add_filter( 'woocommerce_login_redirect', 'filter_woocommerce_login_redirect', 10, 2 );

Redirect user based on custom metadata, wordpress/woocommerce

I have added some custom metadata to wordpress per user and would like to redirect each user after login based on this custom metadata.
For instance i have a page called foo and another called bar. User one has a custom key (acCustomerName) in the metadata stating foo. And the other user has bar in his.
Depending on whats inside that field I would like to redirect the first user to http://example.tld/foo and the other to http://example.tld/bar.
I am able to retrieve this information perfectly fine and echo it out directly to test the function but are not able to retrieve that information inside the sencond function named forward_user and would like to know why.
Right now the user is redirected only to http://example.tld only. So it seems like the function does not get the $kundtyp string.
function kundtyp($Uuser) {
$key = 'acCustomerName';
$single = true;
return get_user_meta( $Uuser, $key, $single );
}
function forward_user( $redirect, $user ) {
$kundtyp = kundtyp($user);
$redirect_page_id = url_to_postid( $redirect );
$checkout_page_id = wc_get_page_id( 'checkout' );
if( $redirect_page_id == $checkout_page_id ) {
return $redirect;
}
return site_url( kundtyp( get_current_user_id() ) );
}
add_filter( 'woocommerce_login_redirect', 'forward_user', 1100, 2 );
Here is the updated code, you have to pass the ID of the user object to get_user_meta data function. You were passing the WP_User object to your function. I don't think you can use function get_current_user_id() because the global wp_user object has not been set yet. I checked it and it always returns 0 as the value. This would explain why they provide the $user variable in the filter.
function kundtyp($Uuser) {
$key = 'acCustomerName';
$single = true;
return get_user_meta( $Uuser->ID, $key, $single );
}
function forward_user( $redirect, $user ) {
$kundtyp = kundtyp($user);
$redirect_page_id = url_to_postid( $redirect );
$checkout_page_id = wc_get_page_id( 'checkout' );
if( $redirect_page_id == $checkout_page_id ) {
return $redirect;
}
return site_url( kundtyp( $user ) );
}
add_filter( 'woocommerce_login_redirect', 'forward_user', 1100, 2 );

Woocommerce REST API v2: Issue with adding custom data to orders

I have a site running an old version of Woo v2.5.5 using legacy v3 for the API. I was able to use the action woocommerce_api_order_response to add data to the orders.
Something like:
add_action( 'woocommerce_api_order_response', 'add_testing_api_function', 10, 1 );
function add_testing_api_function( $order_data ) {
$order_data['foo'] = "testing";
return $order_data;
}
This works fine over the older API link:
https://example.com/wc-api/v3/orders?consumer_key=KEY&consumer_secret=SECRET
However, I need to update to Woo v3.3+ and the REST API is server up as:
https://example.com/wp-json/wc/v2/orders?consumer_key=KEY&consumer_secret=SECRET
My custom data no longer appears, and the hook does not appear to work. Is there another I can use?
WC API is indeed a great tool. Adding your own custom data to WC API shop order's response in WooCommerce 3.x can still be achieved as easily as it used to be with the legacy version of the API.
WooCommerce has these prepare filters for most of their API responses (see). Note that the format of them is woocommerce_rest_prepare_{$post_type}, where $post_type is a post type or taxonomy name like shop_orders or product_cat. In WooCommerce 2.7+ some of these filters also have a _object suffix.
As long as our intent is to add custom data to orders, the right filter to use will be woocommerce_rest_prepare_shop_order_object, where shop_order is our {$post_type} followed the _object suffix (as described above).
The following function conditionally gets user meta and returns the user's social profile's avatar url if available.
/**
* Add custom data to WC API shop order response
* Overriding "$object" here with $order so it's easier to access its properties
*/
function my_wc_rest_prepare_order( $response, $order, $request ) {
if( empty( $response->data ) )
return $response;
$order_id = $order->get_id();
// Get an instance of the WC_Order object
$order = wc_get_order($order_id);
// Get the user ID from WC_Order methods
$user_id = $order->get_customer_id(); // $order->get_user_id(); // or $order->get_customer_id();
// check for WooCommerce Social Login User Avatar
if( class_exists( 'WC_Social_Login' ) ) {
$fb_avatar = get_user_meta( $user_id, '_wc_social_login_facebook_profile_image', true );
$gplus_avatar = get_user_meta( $user_id, '_wc_social_login_google_profile_image', true );
}
$social_data = array();
$avatar_url = array();
$customer_picture = array(
'default' => get_avatar_url( $user_id ),
'facebook' => ( $fb_avatar ) ? esc_url( $fb_avatar ) : '',
'google' => ( $gplus_avatar ) ? esc_url( $gplus_avatar ) : ''
);
$response->data['social_data']['avatar_url'] = $customer_picture;
return $response;
}
add_filter( 'woocommerce_rest_prepare_shop_order_object', 'my_wc_rest_prepare_order', 10, 3 );
Result:
[{
"social_data": {
"avatar_url": {
"default": "https://secure.gravatar.com/avatar/6e27402273b47316097247a2057492f8?s=96&d=mm&r=g",
"facebook": "https://graph.facebook.com/2028542057604385/picture?width=150&height=150",
"google": ""
}
},
}]

How to custom user url in BuddyPress and WordPress?

Thanks for support!
I need to custom user url in my page using WordPress and BuddyPress.
This is example:
From: (current)
http://example.com/user/pum_su411
To
http://example.com/user/548234
With 548234 is ID of the user.
I want after completed the custom, all users will have url like above automatically.
Thanks for all solutions!
add this code to your theme functions.php file.
function _bp_core_get_user_domain($domain, $user_id, $user_nicename = false, $user_login = false) {
if ( empty( $user_id ) ){
return;
}
if( isset($user_nicename) ){
$user_nicename = bp_core_get_username($user_id);
}
$after_domain = bp_get_members_root_slug() . '/' . $user_id;
$domain = trailingslashit( bp_get_root_domain() . '/' . $after_domain );
$domain = apply_filters( 'bp_core_get_user_domain_pre_cache', $domain, $user_id, $user_nicename, $user_login );
if ( !empty( $domain ) ) {
wp_cache_set( 'bp_user_domain_' . $user_id, $domain, 'bp' );
}
return $domain;
}
add_filter('bp_core_get_user_domain', '_bp_core_get_user_domain', 10, 4);
function _bp_core_get_userid($userid, $username){
if(is_numeric($username)){
$aux = get_userdata( $username );
if( get_userdata( $username ) )
$userid = $username;
}
return $userid;
}
add_filter('bp_core_get_userid', '_bp_core_get_userid', 10, 2);
function _bp_get_activity_parent_content($content){
global $bp;
$user = get_user_by('slug', $bp->displayed_user->fullname); // 'slug' - user_nicename
return preg_replace('/href=\"(.*?)\"/is', 'href="'.bp_core_get_user_domain($user->ID, $bp->displayed_user->fullname).'"', $content);
}
add_filter( 'bp_get_activity_parent_content','_bp_get_activity_parent_content', 10, 1 );
function _bp_get_activity_action_pre_meta($content){
global $bp;
$fullname = $bp->displayed_user->fullname; // 'slug' - user_nicename
$user = get_user_by('slug', $fullname);
if(!is_numeric($user->ID) || empty($fullname)){
$args = explode(' ', trim(strip_tags($content)));
$fullname = trim($args[0]);
$user = get_user_by('slug', $fullname);
}
return preg_replace('/href=\"(.*?)\"/is', 'href="'.bp_core_get_user_domain($user->ID, $fullname).'"', $content);
}
add_action('bp_get_activity_action_pre_meta', '_bp_get_activity_action_pre_meta');
add_filter('bp_core_get_userid_from_nicename', '_bp_core_get_userid', 10, 2);
Just spent a bit of time going over the documentation, codex and files of BuddyPress and i can find ways of changing the /user/ part of the url but sadly not the /username side of it.
Reading through, it is controlled within the core of BuddyPress and any changes to the core can cause crashes and more than likely to cause problems or overwrites further down the line.
This isn't to say it's not possible though, it is most certainly possible, but it will require a great deal of editing to many many different files, an edit to a number of BuddyPress functions and there are no guarantee's on it working straight out or even working further down the line when files get update.
I would recommend going onto the BuddyPress Trac and putting in a ticket to have the feature added to change user url structure. It would be a cool feature to be able to swap between a username, full name, ID or any other unique identifiable string.
You can access it here: https://buddypress.trac.wordpress.org/
Alternatively, you can try what aSeptik has done above, but make sure to update that file with any changes when BuddyPress updates as well.

Resources