WordPress add_user_meta / update_user_meta not working (resolved) - wordpress

I'm trying to add the _capabilities and _level meta data to existing users in a multisite setup so they also have access to the new section, our forum.
The forum is the 3rd site on the network and I want to grant everyone the basic access rights as Contributor. Some users I already added manually to the usermeta table so I check in the script if the user meta_key already exists or not. And to ensure the script doesn't mess with the admin accounts I only want to run the script for user IDs above 3.
When I try below code, I use it in a temp plugin which I will only run once, then I just get a whole bunch of WordPress error messages thrown at me which I somehow can't really decipher to get it working :(
The issue is somehow with the add_ / update_user_meta functions... What am I overlooking?
$prefix = 'tbl_prefix_3_';
$cap = [ "contributor" => true ];
$lvl = 1;
$users = get_users( array( 'fields' => array( 'ID' ) ) );
asort( $users );
foreach( $users as $user ) {
$user_id = intval( $user->ID );
if( $user_id > 3 ) {
$check = get_user_meta( $user_id, $prefix . 'capabilities', true );
if( empty( $check ) ) {
add_user_meta( $user_id, $prefix . 'capabilities', $cap );
} else {
update_user_meta( $user_id, $prefix . 'capabilities', $cap );
}
$check = get_user_meta( $user_id, $prefix . 'user_level', true );
if( empty( $check ) ) {
add_user_meta( $user_id, $prefix . 'user_level', $lvl );
} else {
update_user_meta( $user_id, $prefix . 'user_level', $lvl );
}
}
}
The errors:
Fatal error: Uncaught Error: Call to undefined function get_user_by()
in /home/.../wp-includes/meta.php:1652 Stack trace:
#0 /home/.../wp-includes/meta.php(176): get_object_subtype('user', 4)
#1 /home/.../wp-includes/user.php(1043): update_metadata('user', 4, 'tbl_prefix_capab...', Array, '')
#2 /home/.../wp-content/plugins/assign_rights_to_users.php(33): update_user_meta(4, 'tbl_prefix_capab...', Array)
#3 /home/.../wp-settings.php(391): include_once('/home/...') #4 /home/.../wp-config.php(253): require_once('/home/...')
#5 /home/.../wp-load.php(37): require_once('/home/...')
#6 /home/.../wp-admin/admin.php(34): require_once('/home/...') #7 /ho in /home/.../wp-includes/meta.php on line 1652
Notice: is_embed was called incorrectly. Conditional query tags do not
work before the query is run. Before then, they always return false.
Please see Debugging in WordPress for more information. (This message
was added in version 3.1.0.) in /home/.../wp-includes/functions.php on
line 5313
Notice: is_search was called incorrectly. Conditional query tags do
not work before the query is run. Before then, they always return
false. Please see Debugging in WordPress for more information. (This
message was added in version 3.1.0.) in
/home/.../wp-includes/functions.php on line 5313
There has been a critical error on this website. Please check your
site admin email inbox for instructions.

I figured it out, I had forgotten to include it in a hook so the WordPress stuff was not properly available in the plugin :|
I now placed it into an admin_init hook so I activate the plugin, let it do it's magic, and than deactivate and remove the plugin again. I also simplified the whole thing, so only using the update_user_meta now.
Anyway, this is the working result:
<?php
/**
* Plugin Name: 000 FIX MISSING USER RIGHTS
* Description: Activate, deactivate, check the results, remove the plugin!
* Version: 1.0
* Author: golabs
* #source: https://stackoverflow.com/a/66877257/3592696
*/
function fix_missing_user_rights() {
$prefix = 'wp_prefix_';
/**
* Use one of the 2 methods:
* - manual array with user ids
* OR
* - collect them from the database
* Just comment out the method you don't want to use.
*/
# $users = [ 1,2,3,4,5,6,7,8,9,10 ];
$users = get_users( array( 'fields' => 'ID' ) ); asort( $users );
foreach( $users as $user ){
update_user_meta( $user, $prefix.'capabilities', [ 'subscriber' => true ] );
update_user_meta( $user, $prefix.'user_level', 0 );
update_user_meta( $user, $prefix.'2_capabilities', [ 'customer' => true ] );
update_user_meta( $user, $prefix.'2_user_level', 8 );
update_user_meta( $user, $prefix.'3_capabilities', [ 'contributor' => true ] );
update_user_meta( $user, $prefix.'3_user_level', 1 );
}
}
add_action( 'admin_init', 'fix_missing_user_rights' );

Related

Add custom bulk action "send email invoice" to orders list in Woocommerce

enter image description here
Hello How are you? I dont know how to bulk this action "email invoice /order details to customer" sometimes i have 70 orders that I need to send the email, and i have to do it one by one, i found some codes here but for other actions and i dont know how i can add that one, thanks a lot for the help!
function write_to_file($date_initial, $date_final) {
global $attach_download_dir, $attach_download_file;
// Opens/creates file
$myfile = fopen($attach_download_dir . '/' . $attach_download_file, "w") or die("Unable to open file!");
// Populates first line
fwrite($myfile, 'Date; Parent Order ID; Order ID' . PHP_EOL);
// Retrieves orders data
if ( isset($date_initial) && isset($date_final) ) $args = array( 'date_created' => $date_initial . '...' . $date_final );
if ( isset($date_initial) && empty($date_final) ) $args = array( 'date_created' => '>=' . $date_initial );
if ( empty($date_initial) && isset($date_final) ) $args = array( 'date_created' => '<=' . $date_final );
if ( empty($date_initial) && empty($date_final) ) $args = array( );
$orders = wc_get_orders( $args );
// Populates file with orders data
foreach ($orders as $order) {
$order_data = $order->get_data();
fwrite($myfile,
// Date of order creation
$order_data['date_created']->date('d/M/Y') . '; ' .
// Parent Order ID
'#' . ( ( $order->get_type() === 'shop_order' ) ? $order->get_id() : $order->get_parent_id() ) . '; ' .
// Order ID
'#' . $order->get_id()
)
}
}
I was looking for how to bulk email woocommerce order emails to customers, and came across this post. I tried asking a similar question - but thanks to 7uc1f3r for kicking my butt to do more work and find this answer myself.
With a bit of perseverance I figured it out by cobbling together a few bits and pieces from various posts.
I started with this post and used the email trigger code from this post.
I've tested this successfully on my production WooCommerce store.
The code below will add a new Bulk action to the WooCommerce -> Orders page called "Email Invoice / Order Details to Customers".
Select all the orders you want to receive the email, and choose this option. It will cycle through and send the WooCommerce template for Invoice/Order Email to each customer for each selected order. It gives a status update of how many emails were sent.
To use it, copy this code into your Wordpress theme's functions.php file:
/* Add to admin order list bulk dropdown a custom action 'Email Invoice / Order Details to Customers' */
add_filter( 'bulk_actions-edit-shop_order', 'email_invoice_bulk_action_orders_list', 20, 1 );
function email_invoice_bulk_action_orders_list( $actions ) {
$actions['send_emails'] = __( 'Email Invoice / Order Details to Customers', 'woocommerce' );
return $actions;
}
// Make the action from selected orders
add_filter( 'handle_bulk_actions-edit-shop_order', 'email_invoice_handle_bulk_action_orders_list', 10, 3 );
function email_invoice_handle_bulk_action_orders_list( $redirect_to, $action, $post_ids ) {
if ( $action !== 'send_emails' )
return $redirect_to; // Exit
$processed_ids = array();
foreach ( $post_ids as $orderid ) {
// Send customer order email
WC()->mailer()->emails['WC_Email_Customer_Invoice']->trigger($orderid);
// update count
$processed_ids[] = $post_id;
}
return $redirect_to = add_query_arg( array(
'send_emails' => '1',
'processed_count' => count( $processed_ids ),
'processed_ids' => implode( ',', $processed_ids ),
), $redirect_to );
}
// The results notice from bulk action on orders
add_action( 'admin_notices', 'email_invoice_bulk_action_admin_notice' );
function email_invoice_bulk_action_admin_notice() {
if ( empty( $_REQUEST['send_emails'] ) ) return; // Exit
$count = intval( $_REQUEST['processed_count'] );
printf( '<div id="message" class="updated fade"><p>' .
_n( 'Sent %s Order Invoice Email.',
'Sent %s Order Invoice Emails.',
$count,
'send_emails'
) . '</p></div>', $count );
}
Please test on a staging site first - just in case!
I hope this helps.
Israel.

WordPress - set display name from nickname with register process

It is possible set display name from entered string into nickname registration field? I trying do this with simple hook, but after all it is not work.
function set_default_display_name( $user_id ) {
$user = get_userdata( $user_id );
$name = $user->nickname;
$args = array(
'ID' => $user_id,
'display_name' => $name
);
wp_update_user( $args );
}
add_action( 'user_register', 'set_default_display_name' );
By default immediately after registration the display name was set from WP username (login) not nickname. Can sombody help me to set a display name from nickname?
// change default display name format
add_action('user_register', 'registration_save_displayname', 1000);
function registration_save_displayname($user_id) {
if ( isset( $_POST['first_name'])){
$pretty_name = $_POST['first_name'];
wp_update_user( array ('ID' => $user_id, 'display_name'=> $pretty_name) ) ;
}
}

Gravity Form save to Database usermeta table

I have created the following wordpress function to save a form created in Gravity Forms to the usermeta database based on one I had working for CF7 but it isn't working, hopefully someone can see where I've made a mistake. It needs to update the current users fields.
add_action('gform_after_submission', 'input_fields', 10, 2);
function input_fields($entry, $form){
$name = $entry['1'];
$email = $entry['4'];
global $wpdb, $current_user;
$wpdb->insert(
'usermeta',
array(
'description' => $email,
'former_name' => $name
)
);
}
I've seen other examples which are pretty much identical so i'm a bit stuck.
This should do the trick:
add_action( 'gform_after_submission', 'input_fields', 10, 2 );
function input_fields( $entry, $form ) {
$name = $entry[1];
$email = $entry[4];
update_user_meta( get_current_user_id(), 'description', $email );
update_user_meta( get_current_user_id(), 'former_name', $name )
}
Alternately, I'd recommend upgrading to a Developer license and getting access to the User Registration add-on which would do this even more easily. :)
Semicolon sign ";" is missing at line 8 so this is right the answer. :)
add_action( 'gform_after_submission', 'input_fields', 10, 2 );
function input_fields( $entry, $form ) {
$name = $entry[1];
$email = $entry[4];
update_user_meta( get_current_user_id(), 'description', $email );
update_user_meta( get_current_user_id(), 'former_name', $name );
}

Change user profile URL in Buddypress with nickname or userID

I am using this code which is partially working for changing the profile url everywhere in buddypress and wordpress from “http:/mywebsite/user/username” to “http:/mywebsite/user/userid”
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 );
add_filter('bp_core_get_userid_from_nicename', '_bp_core_get_userid', 10, 2);
It is working perfectly for me at the moment BUT not on this little place (see picture):
http://i.imgur.com/4dX0RUB.png
– url change of the author of an activity starting-message is not working in both groups activities and personnal activities
url change of the author of an activity REPLY is working
I don’t know if I am explaining very well what issue I have got but I hope you will understand.
Thank you for your answers
PS : thanks to aSeptik from StackExchange for the code
It's impossible to do that on a fly gracefully. BuddyPress Activity component is developed in such a way, that those text with the user link in activity stream (for site-wide, personal and groups) is stored directly in the database as an action. Just take a look at wp_bp_activity.action field in your DB.
So you should filter and preg_replace it as well. I guess you know that you are penalting yourself with rendering speed loss.

How to Auto Login After Registration in WordPress with core php

I've been trying for days now to take users who have just registered to my WordPress site and automatically log them in and then redirect them to a URL of my choice.
By default, WordPress sends you a username and a password, then you must log in manually. This is a total pain. How can i overcome this.
I have my own registration page(core php page) which successfully adds users into DB. But the point is, i should avoid users to login again.
Once registration is done, it should automatically redirects to home page or profile page.
I am a newbie to wordpress functionalities. It would be grateful if someone(who have knowledge on core functionality of wordpress) at least suggests a way/solution.
Looking forward.
Thanks
// Add on function.php for Auto login after register and redirect to a home page. varified this code
function auto_login_new_user( $user_id ) {
wp_set_current_user($user_id);
wp_set_auth_cookie($user_id);
$user = get_user_by( 'id', $user_id );
do_action( 'wp_login', $user->user_login );//`[Codex Ref.][1]
wp_redirect( home_url() ); // You can change home_url() to the specific URL,such as "wp_redirect( 'http://www.wpcoke.com' )";
exit;
}
add_action( 'user_register', 'auto_login_new_user' );
Following is based on how WooCommerce creates a new user and logs him in:
$user_pass = esc_attr( $_POST['account_password'] );
$new_user_data = array(
'user_login' => $_POST['account_username'],
'user_pass' => $user_pass,
'user_email' => $_POST['account_email'],
'role' => 'subscriber'
);
$user_id = wp_insert_user( $new_user_data );
// Set the global user object
$current_user = get_user_by( 'id', $user_id );
// set the WP login cookie
$secure_cookie = is_ssl() ? true : false;
wp_set_auth_cookie( $user_id, true, $secure_cookie );
to redirect use wp_safe_redirect, e.g.
wp_safe_redirect( home_url( '/' ) );
exit;
Instead of touching core files... You can use this
$secure_cookie = is_ssl();
$secure_cookie = apply_filters('secure_signon_cookie', $secure_cookie, array());
global $auth_secure_cookie;
$auth_secure_cookie = $secure_cookie;
wp_set_auth_cookie($user_id, true, $secure_cookie);
$user_info = get_userdata($user_id);
do_action('wp_login', $user_info->user_login, $user_info);
The function wp_create_user returns the just created user_id which you can use to create a cookie and log the user in. If you wish, you can redirect the logged in user to the profile or home page.
Thanks for your support guys..i did on my own with the following code..thanks for your time and support :)
<i>$getdetails= mysql_fetch_array(mysql_query("SELECT * FROM `wp_users` WHERE `ID`='$user_id'"));
$username=$getdetails['user_login'];
$creds = array();
$creds['user_login'] = $username;
$creds['user_password'] = $password;
$creds['remember'] = true;
$user = wp_signon( $creds, false );
if ( is_wp_error($user) ){
echo $user->get_error_message();
}else{
wp_redirect( home_url() );
}

Resources