I am trying to make a wordpress shortcode with a query. I have to make a query of how many orders were made of the products in the last day and in the last week.
I don't know how to filter by date (the date is also in text format). Thank you very much.
Until now I did this:
The Table:
post_id | meta_key | meta_value |
---|---|---|
164 | order_date | 09-12-2020 18:17 |
164 | order_items_5_order_product | chcolate |
164 | order_items_6_order_product | menta |
165 | order_date | 05-12-2020 14:35 |
165 | order_items_1_order_product | chcolate |
165 | order_items_2_order_product | menta |
165 | order_items_3_order_product | granizo |
166 | order_date | 02-10-2020 11:37 |
166 | order_items_5_order_product | chcolate |
166 | order_items_6_order_product | menta |
Query:
SELECT meta_value, COUNT(*) Totales_Pedidos FROM tc_10_postmeta um WHERE meta_key LIKE "order_items_%_order_product" GROUP BY meta_value ORDER BY Totales_Pedidos desc
Result:
meta_key | Totales_Pedidos |
---|---|
chcolate | 3 |
menta | 3 |
granizo | 1 |
Shortcode:
function fln_table_shortcode() {
global $wpdb;
$html = "";
$result = $wpdb->get_results('SELECT meta_value, COUNT(*) Totales_Pedidos FROM tc_10_postmeta um WHERE meta_key LIKE "order_items_%_order_product" GROUP BY meta_value ORDER BY Totales_Pedidos desc');
$count = $wpdb->num_rows;
if($count >0){
$html .="<table>";
$html .="<tr><td><strong>PRODUCT</strong></td><td><strong>NUMBER OF ORDERS</strong></td></tr>";
$html .="<tr>";
foreach($result as $r){
$html .="<td>".$r->meta_value."</td>";
$html .="<td>".$r->Totales_Pedidos."</td>";
$html .="</tr>";
}
$html .="</table>";
}
return $html;
}
add_shortcode( 'table_shortcode','fln_table_shortcode');
Basically you must use a pivot table and prepared statements to generate a dynamic table
db<>fiddle here