I have a plugin with stores user activity in the table wp_usermeta and under meta_key user_last_activity and meta_value something like a:12:{} where 12 is the user id.
So, If I was logged in as user with id: 12 my current page would run this code:
$user = get_user_id();
$activity = get_user_meta($userid, 'user_last_activity', true);
var_dump($activity);
so, that's pretty much it. Except, if I was logged as admin, I would like to see ALL activity by all users.
So, is there anyway to get all user meta? currently I am blindingly doing
foreach(range(1, 1000) as $value){
$activity = get_user_meta($value, 'user_last_activity', true);
var_dump($activity);
}
I am offcourse assuming there are 1000 users, but you can see the limitations.
I would advise to do a single query for the user_meta instead of running get_user_meta within a foreach-loop.
global $wpdb;
$results = $wpdb->get_results("
SELECT user_id, meta_value as 'user_last_activity'
FROM $wpdb->usermeta
WHERE `meta_key` = 'user_last_activity'
");
var_dump($results);
You can use the get_users() function to get all of the users on your site, and then loop through those to grab the user activity.
$users = get_users(); // get array of WP_User objects
foreach ( $users as $user ) {
$activity = get_user_meta( $user->ID, 'user_last_activity', true );
var_dump( $activity );
}
Related
I have a ACF select field with a field name of "sales_rep". It is populated with:
John Doe
Bart Simpson
Eric Cartman
The field is set to show on the "User Form" and only show when the "Current User Role" is an admin.
The field shows on each user page and I can manually change it to the sales rep I want and save it.
The issue is that I want to be able to programmatically update it whenever the user profile is saved. I will eventually add more code to determine the sales rep but I simplified the issue for this post.
Below is my code in functions.php:
Attempt 1: No error and no change to value
// Update sales rep
add_action( 'edit_user_profile_update', 'update_rep' );
add_action( 'personal_options_update', 'update_rep' );
function update_rep( $user_id )
{
update_user_meta( $user_id, 'sales_rep', 'Eric Cartman' );
}
Attempt 2: No error and no change to value
// Update sales rep
add_action( 'edit_user_profile_update', 'update_rep' );
add_action( 'personal_options_update', 'update_rep' );
function update_rep( $user_id )
{
$field_key = "sales_rep";
$value = array("Eric Cartman");
update_field( $field_key, $value, $user_id );
}
Seems like user_ prefix could fix the issue.
Try to get/update fields with user_ prefix.
F.e:
update_field( $field_key, $value, "user_$user_id" );
And for update_user_meta,
Calling delete_user_meta before could solve the problem.
User meta could have duplicate keys.
Try this one
delete_user_meta( $user_id, $field_key );
add_user_meta( $user_id, $field_key, $value );
I think #Andrii Kovalenko is right, user_ prefix could be your issue.
Also noticed you are saving acf field data as an array("Eric Cartman").
I am assuming your ACF select field predefined select options look like this...
John Doe
Bart Simpson
Eric Cartman
This should work for your acf option...
// is run when you edit YOUR profile, and save it
add_action('personal_options_update', 'handle_user_profile_update' );
// is run when you edit ANY OTHER profile and save it
add_action('edit_user_profile_update', 'handle_user_profile_update' );
// on user profile update function handler
function handle_user_profile_update($user_id) {
// update sales rep
update_sales_rep_field($user_id);
// add anymore on user update profile functions here...
}
// update sales rep field
function update_sales_rep_field($user_id) {
// our values
$value = 'Eric Cartman';
// update acf user field by user id
update_field('sales_rep', $value, 'user_' . $user_id);
}
Out of curiosity, are these sales reps actually users in your wordpress site?
If so you can dynamically populate the select sales_rep user field with sales rep users on your site like this...
function render_sales_rep_select_field($field) {
// reset sales_rep select field choices
$field['choices'] = [];
// get users with user role sales
$args = array(
'role' => 'sales', // your sales reps user role
'orderby' => 'user_nicename',
'order' => 'ASC'
);
// get user with args from above
$users = get_users( $args );
// for each sales rep user
foreach ( $users as $user ) {
// build our sales rep select field choices by user_id > full name
$field['choices'][$user->id] = $user->first_name . ' ' . $user->last_name
}
// return the select field
return $field;
}
// load user field with our custom select drop of sales rep users
add_filter('acf/load_field/name=sales_rep', 'render_sales_rep_select_field');
With this method you won't need to update the field when the user saves changes to their profile.
For example if you get_field like this...
// get user field sales rep array
get_field('sales_rep', 'user_' . $user_id ); // random user id
it will return an array of user_id and full name...
Array
(
[5] => Eric Cartman
)
In your acf user select field settings you will need select return both value and label.
I need to change the user rol when a user visit any page of my site based in the value of data in database.
In my DB in the wp_usermeta has this row:
The meta_value can take the values 1 and 0.
Then, I need to add a hook to be fired when any page of the site is loaded to run a code which will change the user role to "myCustomRole" when the 'meta_value' of 'meta_key' is '1'. Something like:
add_action('template_redirect', 'hooker');
function hooker(){
$id_logged_user = $current_user_id = get_current_user_id();
$table_name = "wp_usermeta";
$results = $wpdb->get_results( "SELECT * FROM $table_name WHERE 'user_id' == $id_logged_user && 'meta_value' == 1 && 'meta_key'== 'wpuef_cid_c17');
if($results) {
$wp_user_object = new WP_User($current_user->ID);
$wp_user_object->set_role('my_custom_role');
}
}
init hook is better to update user role.
add_action('init', 'changeUserRole');
function changeUserRole()
{
$user_id = get_current_user_id();
$user_meta = get_user_meta($user_id, 'wpuef_cid_c17', true);
if ($user_meta == 1) {
$user = new WP_User( $user_id );
$user->set_role( 'my_custom_role' );
}
}
I have a project where a user can actually delete their own virtual product they have put up for sale and there may actually be some active orders on that product at the time of its deletion. I figured the best solution would be to add a cronjob that runs every 10 minutes, using a real cron, via crontab, rather than the Wordpress virtual cron, which I have already enacted - but the question is, how do I get all of the orders for a product and then change the status of all of those products to cancelled rather than deleting them, for posterity.
Any help will be appreciated, thank you.
So, worked it out... safer and just generally better way of doing this. Rather than a cronjob, you hook on post deletion and when a product is actually deleted you perform the query required. You find all the attached orders that are not already complete and you cancel those upcoming / pending orders.
function get_order_ids_by_product_id( $product_id, $order_status = array( 'wc-completed' ) ){
global $wpdb;
$results = $wpdb->get_col("
SELECT order_items.order_id
FROM {$wpdb->prefix}woocommerce_order_items as order_items
LEFT JOIN {$wpdb->prefix}woocommerce_order_itemmeta as order_item_meta ON order_items.order_item_id = order_item_meta.order_item_id
LEFT JOIN {$wpdb->posts} AS posts ON order_items.order_id = posts.ID
WHERE posts.post_type = 'shop_order'
AND posts.post_status NOT IN ( '" . implode( "','", $order_status ) . "' )
AND order_items.order_item_type = 'line_item'
AND order_item_meta.meta_key = '_product_id'
AND order_item_meta.meta_value = '$product_id'
");
return $results;
}
add_action( 'before_delete_post', 'check_for_active_orders' );
function check_for_active_orders($post_id){
$WC_Product = wc_get_product( $post_id );
$orders_ids = get_order_ids_by_product_id( $post_id );
if(count($orders_ids) > 0){
foreach($orders_ids as $oid){
$order = new WC_Order($oid);
$order->update_status('cancelled', 'This product has been removed.');
}
}
}
Hopefully it'll help someone else in the near future.
how i can get the users nice name in a function?
currently i got it with an avatar, but dont know hot to get the users nice name:
$table = $wpdb->prefix . "thumbsup_info";
$result = $wpdb->get_results("SELECT userid FROM $table WHERE postid = '$postid' LIMIT 10", ARRAY_A);
$total_user = $wpdb->num_rows;
for($i=0; $i <$total_user ; $i++)
{
$userid.= get_avatar($result[$i]['userid'],100);
}
return $userid;
Get the user object with the following line of code:
$user = get_user_by( 'id', $result[$i]['userid'] );
Then you can just access the property you need. To get the nicename for example you would use $user->data->user_nicename
I am attempting to carry out a few functions when a user registers on a wordpress site. I have created a module for this which carries out the following function:
add_action( 'user_register', 'tml_new_user_registered' );
function tml_new_user_registered( $user_id ) {
//wp_set_auth_cookie( $user_id, false, is_ssl() );
//wp_redirect( admin_url( 'profile.php' ) );
$user_info = get_userdata($user_id);
$subscription_value = get_user_meta( $user_id, "subscribe_to_newsletter", TRUE);
if($subscription_value == "Yes") {
//include("Subscriber.Add.php");
}
echo "<pre>: ";
print_r($user_info);
print_r($subscription_value);
echo "</pre>";
exit;
}
But it seems that i am not able to access any user meta data as at the end of this stage none of it is stored.
Any ideas how i execute a function once Wordpress has completed the whole registration process of adding meta data into the relevant tables too?
I attempted to use this:
add_filter('user_register ','tml_new_user_registered',99);
But with no luck unfortunately.
Thanks in advance!
I read at the action reference api page that the user id is passed as user ID. Try substituting your $user_id for $user_ID.
I don't think the user metadata is available at the point where this action hook is triggered. From the Codex
"Not all user meta data has been stored in the database when this action is triggered. For example, nickname is in the database but first_name and last_name are not (as of 3.9.1). The password has already been encrypted when this action is triggered."