Last active
August 18, 2023 08:27
-
-
Save dantetesta/fbea8ad273e3636b155910c9db1ff5b3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php /* | |
SOMA VALORES DE UM CAMPO DE CPT DO USUÁRIO CORRENTE | |
PARA USAR ==> [total_cpt cpt='lancamentos' key='_valor' query='_tipo' valor='Receita'] | |
*/ | |
function soma_valores_cpt_dante_testa($atts) { | |
$user_id = get_current_user_id(); // Obtenha o ID do usuário corrente | |
// Obtenha o nome do metafield a partir dos parâmetros do shortcode | |
$metafield = shortcode_atts(array( | |
'cpt' => 'posts', | |
'key' => '_valor' | |
), $atts); | |
$args = array( | |
'post_type' => $metafield['cpt'], | |
'posts_per_page' => -1, | |
'meta_key' => $metafield['key'], | |
'author' => $user_id | |
); | |
$query = new WP_Query($args); // Execute a consulta | |
$total_valor = 0; // Inicialize a soma dos valores | |
if ($query->have_posts()) { | |
while ($query->have_posts()) { | |
$query->the_post(); | |
$valor = get_post_meta(get_the_ID(), $metafield['key'], true); // Obtenha o valor do meta campo | |
$valor = str_replace(".", "", $valor); | |
$valor = str_replace(",", ".", $valor); | |
$valor = floatval(str_replace(array("R$"," "), "", $valor)); | |
$total_valor += floatval($valor); // Adicione o valor à soma total | |
} | |
} | |
wp_reset_postdata(); // Restaure os dados do post original | |
return 'R$' . number_format($total_valor, 2, ',', '.'); // Retorne o total formatado | |
} | |
add_shortcode('total_cpt', 'soma_valores_cpt_dante_testa'); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment