Skip to content

Instantly share code, notes, and snippets.

@dantetesta
Last active August 18, 2023 08:27
Show Gist options
  • Save dantetesta/fbea8ad273e3636b155910c9db1ff5b3 to your computer and use it in GitHub Desktop.
Save dantetesta/fbea8ad273e3636b155910c9db1ff5b3 to your computer and use it in GitHub Desktop.
<?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