Skip to content

Instantly share code, notes, and snippets.

@emanweb
Last active May 24, 2022 12:08
Show Gist options
  • Save emanweb/3272d93d481e8c749edaa2cce2641b28 to your computer and use it in GitHub Desktop.
Save emanweb/3272d93d481e8c749edaa2cce2641b28 to your computer and use it in GitHub Desktop.
Relatório de vendas por ano e estado brasilero para WooCommerce
/**
* @snippet Relatorio de vendas por ano e estado brasileiro @ WooCommerce Admin
* @sourcecode https://gist.github.com/emanweb/3272d93d481e8c749edaa2cce2641b28
* @author Emanuel Costa
* @testedwith WooCommerce 6.3.1
* @inspiredby https://businessbloomer.com/?p=72853 (Rodolfo Melogli)
* @instructions Inclua esse código no functions.php to seu tema filho (child theme)
*/
// -----------------------
// 1. Create extra tab under Reports / Orders (Esse relatório aparece na opção Menu > Relatorios > Vendas por Estado
add_filter( 'woocommerce_admin_reports', 'htw_admin_add_report_orders_tab' );
function htw_admin_add_report_orders_tab( $reports ) {
$array = array(
'sales_by_state' => array(
'title' => 'Vendas por Estado',
'description' => '',
'hide_title' => 1,
'callback' => 'htw_yearly_sales_by_state'
)
);
$reports['orders']['reports'] = array_merge($reports['orders']['reports'],$array);
return $reports;
}
// -----------------------
// 2. Calculate sales by state
function htw_yearly_sales_by_state() {
$year = 2021; // change this if needed
$args = [
'post_type' => 'shop_order',
'posts_per_page' => '-1',
'year' => $year,
'post_status' => ['wc-completed']
];
$my_query = new WP_Query($args);
$orders = $my_query->posts;
$brArr = array();
//$salesArr = array();
$brTotal = 0;
foreach ($orders as $order => $value)
{
$order_id = $value->ID;
$order = wc_get_order($order_id);
$order_data = $order->get_data();
if ( $order_data['billing']['country'] === 'BR' ) {
$myTotal = $order->get_total();
$brTotal += $myTotal;
$brArr[$order_data['billing']['state']] += $myTotal;
}
}
arsort($brArr);
echo "<h2>Vendas por estado para ano de " . $year . " no Brasil:</h2>";
foreach($brArr as $brState => $brSalesValue)
{
echo $brState . ": " . wc_price($brSalesValue) . "<br/>";
}
echo "<h3>Total de Vendas: " . $brTotal."</h3>";
echo "";
echo "<h2>Vendas percentual por estado para ano de " . $year . " no Brasil:</h2>";
foreach($brArr as $brState => $brSalesValue)
{
echo $brState . ": " . round(($brSalesValue/$brTotal)*100,2) . "%<br/>";
}
echo "";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment