How to identify the user at the time of the first LOGIN, change the ROLE and redirect to a specific page all at once? - wordpress

I imported into the WordPress database (WPDB) a table created by me to serve as a reference and way of comparing the data with the WP USERMETA table in WordPress. The most important column in this extra table, WP USER CONTROL, is the one that contains my users' emails. My intention is that at the time of the first LOGIN, the code (which is in the "functions.php" file) compares the user's email with that of the extra WP USER CONTROL table with the email in WP USER META, if the e-mail is in both, it means that it will change the user's ROLE (and some records of the WP USERMETA table, in the WPDB). With the records changed according to what was updated in the WPDB, the user will be redirected to the appropriate page for that ROLE.
`
function shapeSpace_register_add_meta( $user_id ) { add_user_meta( $user_id, "_new_user", "1" ); }
add_action( "user_register", "shapeSpace_register_add_meta" );
function shapeSpace_first_user_login( $user_login, $user ) {
$new_user = get_user_meta( $user -> ID, "_new_user", true );
if ( $new_user ) {
update_user_meta( $user -> ID, "_new_user", "0" );
function userDataCheck( $userData ) {
$table = $wpdb -> prefix . "perfis_usuario_controle";
$emailperfisusuario = $wpdb -> get_results( $wpdb -> prepare ( "SELECT * FROM `{$table}` ORDER BY `{$table}` . `email` ASC" ), ARRAY_A );
if ( ! empty( $userData["user_email"] ) ) {
$usEmail = $userData["user_email"];
$user = get_user_by( "email", $usEmail );
$userId = $user -> ID;
// Capabilities
$capabilities = $wpdb -> get_var( $wpdb -> prepare( "SELECT * FROM `{$table}` . `role` WHERE `{$table}` . `id` = "{$userId}"" ) );
switch ( $capabilities ) {
case "Docente" :
$cap = "a:1:{s:7:"docente";b:1;}";
break;
case "Secretaria" :
$cap = "a:1:{s:10:"secretaria";b:1;}";
break;
case "Direção" :
$cap = "a:1:{s:7:"direcao";b:1;}";
break;
}
$nomecompleto = $wpdb -> get_var( $wpdb -> prepare( "SELECT * FROM `{$table}` . `nome` WHERE `{$table}` . `id` = "{$userId}"" ) );
$arr_nome = explode( " ", $nomecompleto ); // Array
$primeiro_nome = $arr_nome[0]; // first_name (string)
$arr_nome2 = array_splice( $arr_nome, 0, 1 ); // Array (without zero)
$sobrenome = implode( " ", $arr_nome2 ); // last_name (string)
// Site (personal)
$sitepessoal = $wpdb -> get_var( $wpdb -> prepare( "SELECT * FROM `{$table}` . `site` WHERE `{$table}` . `id` = "{$userId}"" ) );
// Curriculum
$currlattes = $wpdb -> get_var( $wpdb -> prepare( "SELECT * FROM `{$table}` . `curriculum` WHERE `{$table}` . `id` = "{$userId}"" ) );
// Departament
$departament = $wpdb -> get_var( $wpdb -> prepare( "SELECT * FROM `{$table}` . `departamento` WHERE `{$table}` . `id` = "{$userId}"" ) );
switch ( $departament ) {
case 1 :
$departamento = "Departamento de Análise Matemática (Departamento I) ";
break;
case 2 :
$departamento = "Departamento de Estruturas Matemáticas (Departamento II) ";
break;
case 3 :
$departamento = "Departamento de Geometria e Representação Gráfica (Departamento III) ";
break;
case 4 :
$departamento = "Departamento de Informática e Ciência da Computação (Departamento IV) ";
break;
case 5 :
$departamento = "Departamento de Estatística (Departamento V) ";
break;
case 6 :
$departamento = "Departamento de Matemática Aplicada (Departamento VI) ";
break;
case 7 :
$departamento = "Secretaria";
break;
case 8 :
$departamento = "Direção";
break;
default :
$departamento = "";
break;
}
$chefdepto = $wpdb -> get_var( $wpdb -> prepare( "SELECT * FROM `{$table}` . `chefdepto` WHERE `{$table}` . `id` = "{$userId}"" ) );
if ( $chefdepto == 0 )
{
$chefdep = "Não";
}
else if ( $chefdepto == 1 )
{
$chefdep = "Sim";
}
$subchefdepto = $wpdb -> get_var( $wpdb -> prepare( "SELECT * FROM `{$table}` . `subchefdepto` WHERE `{$table}` . `id` = "{$userId}"" ) );
if ( $subchefdepto == 0 )
{
$subchefdep = "Não";
}
else if ( $subchefdepto == 1 ) {
$subchefdep = "Sim";
}
if ( in_array( $userData["user_email"], $emailperfisusuario ) ) {
// update_user_meta( int $user_id, string $meta_key, mixed $meta_value, mixed $prev_value = "" ) : int|bool
update_user_meta( $userData["user_id"], "ime_wp_capabilities", $cap ); // capabilities (role)
update_user_meta( $userData["user_id"], "first_name", $primeiro_nome ); // first_name
update_user_meta( $userData["user_id"], "last_name", $sobrenome ); // last_name
update_user_meta( $userData["user_id"], "nickname", $primeiro_nome ); // nickname
// wp_update_user( array|object|WP_User $userdata ) : int|WP_Error
wp_update_user(
array(
"ID" => $userData["user_id"],
"user_url" => $sitepessoal
)
);
update_user_meta( $userData["user_id"], "curriculum-lattes", $currlattes ); // curriculum
update_user_meta( $userData["user_id"], "chefe_de_departamento", $chefdep );
update_user_meta( $userData["user_id"], "subchefe_de_departamento", $subchefdep );
update_user_meta( $userData["user_id"], "departamento", $departamento ); // departament
}
return $userData;
}
add_filter( "user_meta_pre_user_register", "userDataCheck" );
}
}
}
add_action( "wp_login", "shapeSpace_first_user_login", 10, 2 );
function login_redirect_based_on_roles( $user_login, $user )
{
if (
in_array( "administrator", $user -> roles ) ||
in_array( "docente", $user -> roles ) ||
in_array( "secretaria", $user -> roles ) ||
in_array( "direcao", $user -> roles )
)
{
exit( wp_redirect( home_url( "/usuario/" ) ) );
}
else
{
exit( wp_redirect( admin_url() ) );
}
}
add_action( "wp_login", "login_redirect_based_on_roles", 10, 2 );
`
After LOGIN, WordPress registers the user as a Subscriber and goes to the Dashboard page. It's not working and I don't know where I'm going wrong. Maybe my approach is not correct, if you have any suggestions thank you very much for your help.

Related

How to make credits accrue not only for new reviews, but for all user reviews?

At the moment I'm using the code below, it only gives credits for 1 new user review... I tried to change the code, but all my attempts are unsuccessful... an example of what I want to do: a user leaves 10 reviews for one product, for each feedback he should receive 1 dollar, that is, 10 x 1 = 10 dollars. I want to set up so that credits are awarded not only for new reviews, but for all any user reviews. I would be very grateful for any help!
/**
* Process new product review action.
*
* #param int $comment_id comment_id.
* #param bool $comment_approved comment_approved.
* #param array $commentdata commentdata.
*/
public function new_product_review( $comment_id, $comment_approved, $commentdata ) {
if ( 'product' === get_post_type( absint( $commentdata['comment_post_ID'] ) ) ) {
if ( ! $this->is_enabled() || 1 !== $commentdata['comment_approved'] || get_comment_meta( $comment_id, 'wallet_transaction_id', true ) || get_post_meta( $commentdata['comment_post_ID'], "_woo_wallet_comment_commission_received_{$commentdata['user_id']}", true ) ) {
return;
}
$this->amount = apply_filters( 'woo_wallet_product_review_action_amount', $this->settings['amount'], $comment_id, $commentdata['user_id'] );
$product = wc_get_product( $commentdata['comment_post_ID'] );
if ( $this->amount && $product && apply_filters( 'woo_wallet_product_review_credit', true, $commentdata ) ) {
$transaction_id = woo_wallet()->wallet->credit( $commentdata['user_id'], $this->amount, sanitize_textarea_field( $this->settings['description'] ) );
update_comment_meta( $comment_id, 'wallet_transaction_id', $transaction_id );
update_post_meta( $commentdata['comment_post_ID'], "_woo_wallet_comment_commission_received_{$commentdata['user_id']}", true );
do_action( 'woo_wallet_after_product_review', $transaction_id, $comment_id );
}
}
}
/**
* Credit new product review.
*
* #param string $new_status new_status.
* #param string $old_status old_status.
* #param object $comment comment.
*/
public function woo_wallet_product_review_credit( $new_status, $old_status, $comment ) {
$product = wc_get_product( $comment->comment_post_ID );
if ( ! $this->is_enabled() || 'approved' !== $new_status || get_comment_meta( $comment->comment_ID, 'wallet_transaction_id', true ) || get_post_meta( $product->get_id(), "_woo_wallet_comment_commission_received_{$comment->user_id}", true ) ) {
return;
}
$this->amount = apply_filters( 'woo_wallet_product_review_action_amount', $this->settings['amount'], $comment->comment_ID, $comment->user_id );
if ( $this->amount && $product && apply_filters( 'woo_wallet_product_review_credit', true, $comment ) ) {
$transaction_id = woo_wallet()->wallet->credit( $comment->user_id, $this->amount, sanitize_textarea_field( $this->settings['description'] ) );
update_comment_meta( $comment->comment_ID, 'wallet_transaction_id', $transaction_id );
update_post_meta( $product->get_id(), "_woo_wallet_comment_commission_received_{$comment->user_id}", true );
do_action( 'woo_wallet_after_product_review', $transaction_id, $comment->comment_ID );
}
}
}

Update Parent Product Quantity When Variation Quantity Changes

I am actually trying to update the stock quantity of parent products whenever the quantity of any of its variation increases or decreases.
What could be the error in following code.
function wc_get_variable_product_stock_quantity( $output = 'raw', $product_id = 0 ){
global $wpdb, $product;
// Get the product ID (can be defined)
$product_id = $product_id > 0 ? $product_id : get_the_id();
// Check and get the instance of the WC_Product Object
$product = is_a( $product, 'WC_Product' ) ? $product : wc_get_product($product_id);
// Only for variable product type
if( $product->is_type('variable') ){
// Get the stock quantity sum of all product variations (children)
$stock_quantity = $wpdb->get_var("
SELECT SUM(pm.meta_value)
FROM {$wpdb->prefix}posts as p
JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
WHERE p.post_type = 'product_variation'
AND p.post_status = 'publish'
AND p.post_parent = '$product_id'
AND pm.meta_key = '_stock'
AND pm.meta_value IS NOT NULL
");
// Preparing formatted output
if ( $stock_quantity > 0 ) {
$html = '<p class="stock in-stock">'. sprintf( __("%s in stock", "woocommerce"), $stock_quantity ).'</p>';
} else {
if ( is_numeric($stock_quantity) )
$html = '<p class="stock out-of-stock">' . __("Out of stock", "woocommerce") . '</p>';
else
$html = '';
}
// Different output options
if( $output == 'echo_html' )
echo $html;
elseif( $output == 'return_html' )
return $html;
else
return $stock_quantity;
}
}

Update Product Stock When Variation Stock Changes in WooCommerce

I am trying the update total stock of the product when stock for any variation changes. I want to keep the total stock of all the variations updated.
Here is the code I am using but it's not working. What could be the reason.
add_action( 'woocommerce_product_set_stock', 'wc_get_variable_product_stock_quantity' );
function wc_get_variable_product_stock_quantity( $output = 'raw', $product_id = 0 ){
global $wpdb, $product;
// Get the product ID (can be defined)
$product_id = $product_id > 0 ? $product_id : get_the_id();
// Check and get the instance of the WC_Product Object
$product = is_a( $product, 'WC_Product' ) ? $product : wc_get_product($product_id);
// Only for variable product type
if( $product->is_type('variable') ){
// Get the stock quantity sum of all product variations (children)
$stock_quantity = $wpdb->get_var("
SELECT SUM(pm.meta_value)
FROM {$wpdb->prefix}posts as p
JOIN {$wpdb->prefix}postmeta as pm ON p.ID = pm.post_id
WHERE p.post_type = 'product_variation'
AND p.post_status = 'publish'
AND p.post_parent = '$product_id'
AND pm.meta_key = '_stock'
AND pm.meta_value IS NOT NULL
");
// Preparing formatted output
if ( $stock_quantity > 0 ) {
$html = '<p class="stock in-stock">'. sprintf( __("%s in stock", "woocommerce"), $stock_quantity ).'</p>';
} else {
if ( is_numeric($stock_quantity) )
$html = '<p class="stock out-of-stock">' . __("Out of stock", "woocommerce") . '</p>';
else
$html = '';
}
// Different output options
if( $output == 'echo_html' )
echo $html;
elseif( $output == 'return_html' )
return $html;
else
return $stock_quantity;
set_stock_quantity( $stock_quantity );
}
}

woocommerce variable product price on dropdown

Hello I m trying to make available the prices for the variations on the dropdown, at some point I were able to achieve it when were only one variable, but now I have two variables for the product but the price on the dropdown is not updating.
Based on Variable product attribute: Customizing each displayed radio buttons text value answer code, here is the code I use to get on the first step, but I need help to update the price of variations up to the second variable selected.
add_filter( 'woocommerce_variation_option_name', 'display_price_in_variation_option_name' );
function display_price_in_variation_option_name( $term ) {
global $wpdb, $product;
if ( empty( $term ) ) return $term;
if ( empty( $product->id ) ) return $term;
$id = $product->get_id();
$result = $wpdb->get_col( "SELECT slug FROM {$wpdb->prefix}terms WHERE name = '$term'" );
$term_slug = ( !empty( $result ) ) ? $result[0] : $term;
$query = "SELECT postmeta.post_id AS product_id
FROM {$wpdb->prefix}postmeta AS postmeta
LEFT JOIN {$wpdb->prefix}posts AS products ON ( products.ID = postmeta.post_id )
WHERE postmeta.meta_key LIKE 'attribute_%'
AND postmeta.meta_key != 'attribute_pa_alto'
AND postmeta.meta_value = '$term_slug'
AND products.post_parent = $id";
$variation_id = $wpdb->get_col( $query );
$parent = wp_get_post_parent_id( $variation_id[0] );
if ( $parent > 0 ) {
$_product = new WC_Product_Variation( $variation_id[0] );
//EDITADO PARA MOSTRAR CUANDO NO HAY STOCK MUESTRA AGOTADO
if($_product->managing_stock() && $_product->get_stock_quantity() < 1){
return $term . ' - AGOTADO';
}else{
return $term . ' - (' . wp_kses( woocommerce_price( $_product->get_price() ), array() ) . ')';
}
}
return $term;
}

Woo-commerce Booking - Fetch all available bookings based on Time Range

I'm trying to fetch bookings based on time availability in wocommerce bookings by passing the time selection in below format:
2019-08-26 08:00 - 2019-08-26 11:00
$available_blocks = $booking_form->product->get_available_blocks( array(
'blocks' => $blocks_in_range,
'from' => $from,
'to' => $to));
foreach ( $available_blocks as $check ) {
if ( true === $booking_form->product->check_availability_rules_against_date( $check, '' )){
//Custom Added to fetch only blocks in selected range
if( $from >= reset($available_blocks) && $to <= end($available_blocks)){
$matches[] = $post_id;
break; // check passed
}
}
}
But, it's only working when I pass time in Hour only format(10:00 AM), When I add minute(10:30 AM) it is not returning any available bookings.
Full function for reference.
/**
* Get all available booking products
*
* #param string $start_date_raw YYYY-MM-DD format
* #param string $end_date_raw YYYY-MM-DD format
* #param int $quantity Number of people to book
* #param string $behavior Whether to return exact matches
* #return array Available post IDs
*/
function get_available_bookings( $start_date_raw, $end_date_raw, $quantity = 1, $behavior = 'default' ) {
$matches = array();
// Separate dates from times
$start_date = explode( ' ', $start_date_raw );
$end_date = explode( ' ', $end_date_raw );
// If time wasn't passed, define defaults.
if ( ! isset( $start_date[1] ) ) {
$start_date[1] = '00:00';
}
$start = explode( '-', $start_date[0] );
$args = array(
'wc_bookings_field_resource' => 0,
'wc_bookings_field_persons' => $quantity,
'wc_bookings_field_duration' => 1,
'wc_bookings_field_start_date_year' => $start[0],
'wc_bookings_field_start_date_month' => $start[1],
'wc_bookings_field_start_date_day' => $start[2],
);
// Loop through all posts
foreach ( $this->product_ids as $post_id ) {
if ( 'product' == get_post_type( $post_id ) ) {
$product = wc_get_product( $post_id );
if ( is_wc_booking_product( $product ) ) {
// Grab the duration unit
$unit = $product->is_type( 'accommodation-booking' ) ? 'night' : $product->get_duration_unit();
// Support time
if ( in_array( $unit, array( 'minute', 'hour' ) ) ) {
if ( ! empty( $start_date[1] ) ) {
$args['wc_bookings_field_start_date_time'] = $start_date[1];
}
}
if ( 'exact' === $behavior ) {
$duration = $this->calculate_duration( $start_date_raw, $end_date_raw, $product->get_duration(), $unit );
$args['wc_bookings_field_duration'] = $duration;
}
$booking_form = new WC_Booking_Form( $product );
$posted_data = $booking_form->get_posted_data( $args );
// All slots are available (exact match)
if ( true === $booking_form->is_bookable( $posted_data ) ) {
$matches[] = $post_id;
}
// Any slot between the given dates are available
elseif ( 'exact' !== $behavior ) {
$from = strtotime( $start_date_raw );
$to = strtotime( $end_date_raw );
$blocks_in_range = $booking_form->product->get_blocks_in_range( $from, $to );
// Arguments changed in WC Bookings 1.11.1
$available_blocks = $booking_form->product->get_available_blocks( array(
'blocks' => $blocks_in_range,
'from' => $from,
'to' => $to
) );
foreach ( $available_blocks as $check ) {
if ( true === $booking_form->product->check_availability_rules_against_date( $check, '' )){
$matches[] = $post_id;
break; // check passed
}
}
}
}
}
}
return $matches;
}

Resources