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' );
}
}
Related
I need some help and I can't seem to figure it out since I'm not exactly sure how to do this.
I have a custom post type called Companies. In the admin user interface, I have created an ACF relationship field to the Companies post type called user_company. Right now I am manually selecting the Companies post based on the user's email address and I would like to do this programatically.
`
function update_user_company( $user_id, $args ) {
$user = get_user_by( 'ID', $user_id );
$email = $user->user_email;
$company = get_field('user_company');
list($user, $domain) = explode('#', $args['user_email'] );
if ($domain == 'gmail.com') {
$company[] = 'Google';
update_field('user_company', $company, $post_title);
};
if ($domain == 'amyling.com') {
$company[] = 'Pearlsin Arts';
update_field('user_company', $company, $post_title);
};
}
add_action( 'user_register', 'update_user_company', 10, 2 );
`
I think your function is correct and the only thing that seems wrong is that you try to update a custom field based on a post title and you should use the post ID or in your case the user ID instead.
So you should try this:
function update_user_company( $user_id, $args ) {
$user = get_user_by( 'ID', $user_id );
$email = $user->user_email;
$company = get_field('user_company');
list($user, $domain) = explode('#', $args['user_email'] );
if ($domain == 'gmail.com') {
$company[] = 'Google';
update_field('user_company', $company, $user_id);
};
if ($domain == 'amyling.com') {
$company[] = 'Pearlsin Arts';
update_field('user_company', $company, $user_id);
};
}
add_action( 'user_register', 'update_user_company', 10, 2 );
Hope this helps
tldr:// how to clone an existing WC_Order_Item_Product to a new order?
I have looked through a lot of existing subscription plugins but didnt really get warm with them. So I decided to create something as a learning project. Its not for a customer, I dont expect it to be commercially successful product, but I guess its good to step up my game.
So I have created a custom table already that saves target dates and would like to create new orders from the existing WC_Order_Item_Product-Objects. By simply adding the original Object it will just move them from the old order, which is something I do not want to happen. I wonder how I could 'clone' the object and remove the protected [order_id] which would be overridden by WC_Order->add_item anyway without altering the original database entries. Maybe thats the wrong approach or a bad idea?
I have also tried to find some up2date hint on how to create a full custom WC_Order_Item_Product but was not really successful on that.
What I got atm:
function update ($reminder_id = null) {
global $woocommerce;
global $wpdb;
global $aboprodukt_table_name;
// TODO if reminder id
if ( ! $reminder_id) {
$neworders = [];
// get all reminders from db and loop through them
$aboprodukt_reminders = $wpdb->get_results( 'SELECT * FROM ' . $aboprodukt_table_name . ' ORDER BY ' . $aboprodukt_table_name . '.targetdate ASC');
foreach ($aboprodukt_reminders as $item ) {
// get original order item object to abstract
$order_item = new \WC_Order_Item_Product($item->orderitem);
// get order object
$order = $order_item->get_order();
// get customer id
$customer = $order->get_customer_id();
// TODO abstract order items
// assign user, adresses if not existing yet, copy from last order
if ( ! $neworders[$customer] ) {
// check all reminders
$customer_array = $order->get_data();
$args = array(
'customer_id' => $customer,
'created_via' => 'Aboprodukt',
'add_order_note' => __('Aboprodukt Custom Order', 'aboprodukt'),
);
$neworders[$customer] = \wc_create_order($args);
// TODO Shipping
}
// add order items
$neworders[$customer]->add_item($order_item);
$neworders[$customer]->calculate_totals();
$neworders[$customer]->save();
}
return print_r($neworders,true);}
Not sure if it helps so. but this is the way I've managed to do so.
For understanding: I got an extra "reminder"-table in the database that stores: date, order-item-id. It is removed after its used to create a new order.
function update ($reminder_id = null) {
global $woocommerce;
global $wpdb;
global $aboprodukt_table_name;
// TODO if order id
if ( ! $reminder_id) {
$neworders = [];
// get all reminders from db and loop through them
$aboprodukt_reminders = $wpdb->get_results( 'SELECT * FROM ' . $aboprodukt_table_name . ' ORDER BY ' . $aboprodukt_table_name . '.targetdate ASC');
foreach ($aboprodukt_reminders as $item ) {
// get original order item object to abstract
$order_item = new \WC_Order_Item_Product($item->orderitem);
$order = $order_item->get_order();
$customer = $order->get_customer_id();
// assign user, adresses if not existing yet, copy from last order
if ( ! $neworders[$customer] ) {
// check all reminders
$args = array(
'customer_id' => $customer,
'created_via' => 'Aboprodukt',
'add_order_note' => __('Aboprodukt Custom Order', 'aboprodukt'),
);
$neworders[$customer] = \wc_create_order($args);
// order
$customer_object = new \WC_Customer( $customer );
$types = array('billing','shipping');
foreach ($types as $type) {
foreach ( $customer_object->{"get_{$type}"}() as $key => $value) {
if ( ! empty($value) ) {
if ( is_callable( array( $neworders[$customer], "set_{$type}_{$key}" ) ) ) {
$neworders[$customer]->{"set_{$type}_{$key}"}( $value );
}
}
}
}
// Set Shipping
$shippingold = $order->get_shipping_methods();
$oldshippingitem = new \WC_Order_Item_Shipping( reset($shippingold) );
$newshippingitem = new \WC_Order_Item_Shipping();
$newshippingitem->set_method_id( $oldshippingitem->get_method_id() );
$newshippingitem->set_instance_id( $oldshippingitem->get_instance_id() );
$newshippingitem->set_method_title( $oldshippingitem->get_method_title() );
$newshippingitem->set_total( $oldshippingitem->get_total() );
$neworders[$customer]->add_item( $newshippingitem );
}
// if variation_id > 0 then is simple product, get product
$item_variation_id = $order_item->get_variation_id();
$item_id = $neworders[$customer]->add_product(
wc_get_product(isset( $item_variation_id ) && $item_variation_id > 0 ? $item_variation_id : $order_item->get_product_id() ),
$order_item->get_quantity()
);
// copy metadata for future use
$neworderitem = new \WC_Order_Item_Product($item_id);
$neworderitem->add_meta_data( '_aboprodukt_order', $order_item->get_meta('_aboprodukt_order'), true );
$neworderitem->add_meta_data( '_aboprodukt_timespan', $order_item->get_meta('_aboprodukt_timespan'), true );
$neworderitem->add_meta_data( '_aboprodukt_type', $order_item->get_meta('_aboprodukt_type'), true );
$neworderitem->save();
$neworders[$customer]->calculate_totals();
$neworders[$customer]->save();
$wpdb->query(
$wpdb->prepare(
"DELETE FROM $aboprodukt_table_name
WHERE id = %d",
$item->id
)
);
}
}
// send emails
foreach ( $neworders as $customers => $neworder ) {
$mailer = \WC()->mailer();
\WC()->mailer()->emails['WC_Email_Customer_Invoice']->trigger($neworder->get_id());
$neworder->add_order_note( sprintf( __('%s email notification manually sent.', 'woocommerce'), $mail->title), false, true);
}
return $neworders;
}
i need to Delete wp_terms -> name field when a user is removed .
my requirement is admin needs to assign posts to specific users, that is admin need to add a post to user1 ,but user2 should not see that.for this i created a custom post and add taxonomy for that.And the terms are users Usernames .so i need to list the usernames of the users as terms in the taxonomy.when a new user is registered his username should updated in the wp_terms table also,so i will get the usernames as terms. this is working well ,now i need to delete the term from taxonomy when the user is removed.
i stucked here .please suggest some solution for this
what i have done is
add_action( 'delete_user', 'yg_user_delete', 10, 1 );
function yg_user_delete( $user_id ) {
$user_info = get_userdata($user_id); $user_name = $user_info->user_login;
print_r($user_info);
wp_delete_term( $user_name, 'user1', array() );
}
There are a few issues with your code.
The main issue is wp_delete_term requires a term_id not a term_name.
You can use wp_get_object_terms to get the term_id for the user.
I haven't tested this code but it should point you in the right direction.
function delete_user_terms( $user_id ) {
$taxonomy = 'user1'; // Change this.
$terms = wp_get_object_terms( $user_id, $taxonomy ); // Get the terms for this user.
if ( is_wp_error( $terms ) ) {
return; // Taxonomy does not exist.
}
foreach ( $terms as $term ) {
wp_delete_term( $term->term_id, $taxonomy ); // This requires Term ID. Not term name.
}
}
add_action( 'delete_user', 'delete_user_terms', 10, 1 );
i got the solution
add_action( 'delete_user', 'yg_user_delete', 10, 1 );
function yg_user_delete( $user_id ) {
$user_info = get_userdata($user_id);
$user_name = $user_info->user_login;
wp_delete_term( get_term_by('name', $user_name, 'user1')->term_id, 'user1', array() );
}
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 );
}
Recently I had a client come to me to build a new website. They had also forgotten all their login details, but they did have FTP access.
How do you create an admin user programmatically in WordPress?
This will create an admin user if placed in a themes functions.php file. Please change the first three variables as needed.
/*
* Create an admin user silently
*/
add_action('init', 'xyz1234_my_custom_add_user');
function xyz1234_my_custom_add_user() {
$username = 'username123';
$password = 'pasword123';
$email = 'drew#example.com';
if (username_exists($username) == null && email_exists($email) == false) {
// Create the new user
$user_id = wp_create_user($username, $password, $email);
// Get current user object
$user = get_user_by('id', $user_id);
// Remove role
$user->remove_role('subscriber');
// Add role
$user->add_role('administrator');
}
}
Accepted answer has issues and will throw a fatal error when its run twice, because the $user_id will be empty the second time. A work around for the issue:
function rndprfx_add_user() {
$username = 'username123';
$password = 'azerty321';
$email = 'example#example.com';
if (username_exists($username) == null && email_exists($email) == false) {
$user_id = wp_create_user( $username, $password, $email );
$user = get_user_by( 'id', $user_id );
$user->remove_role( 'subscriber' );
$user->add_role( 'administrator' );
}
}
add_action('init', 'rndprfx_add_user');
Here is the queries to create a new admin user :
INSERT INTO wp_users (user_login, user_pass, user_nicename, user_email, user_status) VALUES ('newadmin', MD5('pass123'), 'firstname lastname', 'email#example.com', '0');
INSERT INTO wp_usermeta (umeta_id, user_id, meta_key, meta_value) VALUES (NULL, (Select max(id) FROM wp_users), 'wp_capabilities', 'a:1:{s:13:"administrator";s:1:"1";}');
INSERT INTO wp_usermeta (umeta_id, user_id, meta_key, meta_value) VALUES (NULL, (Select max(id) FROM wp_users), 'wp_user_level', '10');
Simply, you need to add this code sample in your functions.php:
function wpb_admin_account(){
$user = 'Username';
$pass = 'Password';
$email = 'email#domain.com';
if ( !username_exists( $user ) && !email_exists( $email ) ) {
$user_id = wp_create_user( $user, $pass, $email );
$user = new WP_User( $user_id );
$user->set_role( 'administrator' );
}
}
add_action('init','wpb_admin_account');
Do not forget to change Username, Password and Email by your own data.
here is more detailed tutorials that might help you.
How to create a new WordPress admin user programmatically