Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // Recently Sold Products shortcode for WooCommerce
- // Version 1.03
- // usage: [sold_products max_products="5" title="Sold Products"]
- // code goes in your child theme's functions.php
- add_shortcode('sold_products', 'sold_products');
- function sold_products($attributes) {
- global $wpdb, $woocommerce;
- $defaults = array('max_products' => 6, 'title' => "Recently Sold Products");
- $parameters = shortcode_atts( $defaults, $attributes);
- $max = absint($parameters['max_products']); // number of products to show
- $title = sanitize_text_field($parameters['title']);
- $html = '<div class="sold_products">'.PHP_EOL;
- if ($title) {
- $html .= '<h3>'.$title.'</h3>'.PHP_EOL;
- }
- $table = $wpdb->prefix.'woocommerce_order_items';
- $my_query = $wpdb->prepare("SELECT * FROM $table WHERE `order_item_type`='line_item' ORDER BY `order_id` DESC LIMIT %d", $max);
- $nr_rows = $wpdb->query($my_query);
- if (!$nr_rows) {
- $html .= '<p>No recently sold products found.</p>';
- } else {
- $html .= '<ul>'.PHP_EOL;
- for ($offset = 0; $offset < $nr_rows; $offset++) {
- $row = $wpdb->get_row($my_query, OBJECT, $offset);
- $product_name = $row->order_item_name;
- $product = get_page_by_title($product_name, OBJECT, 'product');
- $url = get_permalink($product->ID);
- $order_id = $row->order_id;
- $order = new WC_Order($order_id);
- $user = $order->get_user();
- if ($user) {
- $user_id = $user->ID;
- } else {
- $user_id = 'Guest';
- }
- $unix_date = strtotime($order->order_date);
- $date = date('d/m/y', $unix_date);
- $html .= '<li><a href="'.$url.'">'.$product_name.'</a> purchased by user '.$user_id.' on '.$date.'</li>'.PHP_EOL;
- }
- $html .= '</ul>'.PHP_EOL;
- }
- $html .= '</div>'.PHP_EOL;
- return $html;
- } // end function
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement