- March 21, 2024
- Posted by: AliensFaith
- Category: OBJECTIVE PRESS
I know how to use WordPress but I don’t know anything about programming. At my job, they asked me to create something very specific that I can’t do with WordPress alone, so I used ChatGPT to create a custom snippet. The code is working fine, what it does is create a list of all registered customers, and when I place an order I can choose the customer and the order will automatically be assigned to them. However, the problem is that the stock quantity is not decreasing. The order goes through normally but the product stock remains the same. I’ve tried everything, all the AIs, and none of them can fix this. My job depends on this, please help me.
// Shortcode to display the list of customers and assign an order
function mostrar_lista_clientes_shortcode() {
// Verifique se o usuário está logado e é um administrador ou shop manager
if (is_user_logged_in() && (current_user_can(‘administrator’) || current_user_can(‘shop_manager’))) {
// Recupere todos os usuários do tipo ‘customer’
$clientes = get_users(array(‘role’ => ‘customer’));
// Recupere todos os usuários com a função ‘Shop Manager’
$shop_managers = get_users(array(‘role’ => ‘shop_manager’));
// Recupere o ID do usuário logado
$user_id = get_current_user_id();
// Verifique se o usuário logado é um administrador
$admin_default = false;
if (current_user_can(‘administrator’)) {
$admin_default = true;
}
// Verifique se há clientes
if (!empty($clientes) || !empty($shop_managers)) {
$output = ”;
$output .= ‘‘;
$output .= ”;
// Loop através de cada cliente e adicione-o ao dropdown
foreach ($clientes as $cliente) {
$company_name = get_user_meta($cliente->ID, ‘billing_company’, true) ?: $cliente->user_email;
$output .= ‘ID) . ‘”>’ . esc_html($company_name) . ”;
}
$output .= ”;
$output .= ‘
‘;
$output .= ”;
// Adicione o perfil de administrador à lista de Shop Managers apenas se o usuário estiver logado como administrador
if ($admin_default) {
$output .= ‘Admin’;
}
foreach ($shop_managers as $shop_manager) {
$selected = ”;
// Define o valor padrão como o perfil atual do usuário logado
if ($user_id == $shop_manager->ID) {
$selected = ‘selected’;
}
// Obtém o campo de nickname do usuário
$nickname = get_user_meta($shop_manager->ID, ‘nickname’, true);
// Concatena o nickname com o nome de exibição
$name = $shop_manager->display_name;
if ($nickname) {
$name .= ‘ (‘ . $nickname . ‘)’;
}
$output .= ‘ID) . ‘” ‘ . $selected . ‘>’ . esc_html($name) . ”;
}
$output .= ”;
// Obter a data atual e formatá-la no formato desejado (April 30, 2024)
$due_date_default = date(‘F j, Y’);
$output .= ‘
‘;
$output .= ”;
$output .= ”;
$output .= ”;
$output .= ”;
return $output;
} else {
return ‘No customers or shop managers registered.’;
}
} else {
return ‘You need to be logged in as an administrator or shop manager to access this functionality.’;
}
}
add_shortcode(‘mostrar_lista_clientes’, ‘mostrar_lista_clientes_shortcode’);
// Verifique se o formulário foi enviado e processe a atribuição da ordem
function processar_atribuicao_ordem() {
if (isset($_POST[‘atribuir_ordem’]) && isset($_POST[‘cliente_selecionado’]) && isset($_POST[‘vendedor_selecionado’])) {
$cliente_id = intval($_POST[‘cliente_selecionado’]);
$vendedor_id = sanitize_text_field($_POST[‘vendedor_selecionado’]);
$due_date = isset($_POST[‘due_date’]) ? sanitize_text_field($_POST[‘due_date’]) : ”;
$usuario_logado_id = isset($_POST[‘usuario_logado’]) ? sanitize_text_field($_POST[‘usuario_logado’]) : ”;
$usuario_logado = get_userdata($usuario_logado_id);
$usuario_logado_nome = $usuario_logado->user_login;
$usuario_logado_apelido = $usuario_logado->nickname;
// Verifica se há itens no carrinho do cliente
$carrinho_do_cliente = WC()->cart->get_cart();
if (!empty($carrinho_do_cliente)) {
// Criar a ordem
$nova_ordem = wc_create_order(array(
‘customer_id’ => $cliente_id,
‘created_via’ => ‘Manual’,
));
// Verifica se a ordem foi criada com sucesso
if ($nova_ordem) {
// Adiciona produtos do carrinho à ordem
foreach ($carrinho_do_cliente as $item) {
$produto_id = $item[‘product_id’];
$quantidade = $item[‘quantity’];
$produto_obj = wc_get_product($produto_id);
$nova_ordem->add_product($produto_obj, $quantidade);
}
// Define o status da ordem como “On Hold”
$nova_ordem->set_status(‘on-hold’, ‘Status updated automatically upon assigning the order to the customer.’);
// Preenche os detalhes de faturamento
$billing_address = get_user_meta($cliente_id, ‘billing_address_1’, true);
$billing_city = get_user_meta($cliente_id, ‘billing_city’, true);
$billing_state = get_user_meta($cliente_id, ‘billing_state’, true);
$billing_postcode = get_user_meta($cliente_id, ‘billing_postcode’, true);
$billing_country = get_user_meta($cliente_id, ‘billing_country’, true);
$nova_ordem->set_address(array(
‘first_name’ => get_user_meta($cliente_id, ‘first_name’, true),
‘last_name’ => get_user_meta($cliente_id, ‘last_name’, true),
‘address_1’ => $billing_address,
‘city’ => $billing_city,
‘state’ => $billing_state,
‘postcode’ => $billing_postcode,
‘country’ => $billing_country,
), ‘billing’);
// Define a data de vencimento (Due Date) no campo da companhia de entrega (shipping)
$nova_ordem->set_shipping_company($due_date);
// Define o vendedor da ordem
if ($vendedor_id == ‘admin’) {
$vendedor_nome = ‘Admin’;
} else {
$vendedor = get_userdata($vendedor_id);
$vendedor_nome = $vendedor->display_name;
}
$nova_ordem->update_meta_data(‘_shop_manager’, $vendedor_nome);
// Define o usuário logado que fez o pedido
$nova_ordem->update_meta_data(‘_usuario_logado’, $usuario_logado_nome . ‘ (‘ . $usuario_logado_apelido . ‘)’);
// Adiciona o perfil do usuário logado na nota do pedido
$nota_pedido = ‘Logged in profile during order: ‘ . $usuario_logado_nome . ‘ (‘ . $usuario_logado_apelido . ‘)’;
$nova_ordem->add_order_note($nota_pedido);
// Calcular os totais da ordem
$nova_ordem->calculate_totals();
// Salva a ordem
$nova_ordem->save();
// Mensagem de sucesso
echo ‘
Order successfully assigned to customer ID ‘ . $cliente_id . ‘ and to the seller (Shop Manager) ‘ . $vendedor_nome . ‘. Order ID: ‘ . $nova_ordem->get_id() . ‘
‘;
} else {
// Mensagem de erro
echo ‘
An error occurred while assigning the order to customer ID ‘ . $cliente_id . ‘.
‘;
}
} else {
// Mensagem de erro se o carrinho estiver vazio
echo ‘
The customer’s cart is empty. Please add products to the cart before creating the order.
‘;
}
}
}
add_action(‘init’, ‘processar_atribuicao_ordem’);
submitted by /u/blisscypher
[link] [comments]