In woocommerce, I'm trying to create a shortcode to put in my function.php
document, that displays a custom database query on a page.
There's something wrong with it though and i'm not sure what.
function sqlquery_shortcode($atts) {
global $wpdb;
$results = $wpdb->get_results("
SELECT a.order_id, a.order_item_id, a.order_item_name, b.meta_key, b.meta_value
FROM 7pW9iX3L_woocommerce_order_items a
JOIN 7pW9iX3L_woocommerce_order_itemmeta b
ON a.order_item_id = b.order_item_id
JOIN 7pW9iX3L_posts c
ON a.order_id = c.ID
JOIN 7pW9iX3L_postmeta d
ON c.ID = d.post_id
WHERE order_item_type = 'line_item'
");
// Loop through each order post object
foreach($results as $result) {
$order_id = $result->ID; // The Order ID
// Get an instance of the WC_Order Object
$order = wc_get_order( $result->ID );
}
}
add_shortcode("sqlquery_shortcode");
There is many little errors and mistakes. Your SQL query was incorrect, so I have changed in a way to make it work first.
Here is your revisited code to get order line items from your SQL query in an html table. It's just a functional and tested example code, that you should need to change for your needs:
Code goes in function.php file of your active child theme (or active theme). Tested and works.
USAGE:
You will paste that shortcode
[sqlquery_shortcode]
in the Wordpress text editor of a page or a post.Or you can also paste the following in any php template or file:
or in between html tags:
You will get something like: