Advertisement
lorro

WooCommerce - Recently purchased products

Apr 13th, 2015
812
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.90 KB | None | 0 0
  1. <?php
  2.   // Recently Sold Products shortcode for WooCommerce
  3.   // Version 1.03
  4.   // usage: [sold_products max_products="5" title="Sold Products"]
  5.   // code goes in your child theme's functions.php
  6.   add_shortcode('sold_products', 'sold_products');
  7.   function sold_products($attributes) {
  8.     global $wpdb, $woocommerce;
  9.     $defaults = array('max_products' => 6, 'title' => "Recently Sold Products");
  10.     $parameters = shortcode_atts( $defaults, $attributes);
  11.     $max = absint($parameters['max_products']);  // number of products to show
  12.     $title = sanitize_text_field($parameters['title']);
  13.     $html = '<div class="sold_products">'.PHP_EOL;  
  14.     if ($title) {
  15.       $html .= '<h3>'.$title.'</h3>'.PHP_EOL;
  16.     }
  17.     $table = $wpdb->prefix.'woocommerce_order_items';
  18.     $my_query = $wpdb->prepare("SELECT * FROM $table WHERE `order_item_type`='line_item' ORDER BY `order_id` DESC LIMIT %d", $max);  
  19.     $nr_rows = $wpdb->query($my_query);
  20.     if (!$nr_rows) {
  21.       $html .= '<p>No recently sold products found.</p>';
  22.     } else {
  23.       $html .= '<ul>'.PHP_EOL;
  24.       for ($offset = 0; $offset < $nr_rows; $offset++) {
  25.         $row = $wpdb->get_row($my_query, OBJECT, $offset);
  26.         $product_name = $row->order_item_name;
  27.         $product = get_page_by_title($product_name, OBJECT, 'product');
  28.         $url = get_permalink($product->ID);
  29.         $order_id = $row->order_id;
  30.         $order = new WC_Order($order_id);
  31.         $user = $order->get_user();
  32.         if ($user) {
  33.           $user_id = $user->ID;
  34.         } else {
  35.           $user_id = 'Guest';
  36.         }
  37.         $unix_date = strtotime($order->order_date);
  38.         $date = date('d/m/y', $unix_date);
  39.         $html .= '<li><a href="'.$url.'">'.$product_name.'</a> purchased by user '.$user_id.' on '.$date.'</li>'.PHP_EOL;
  40.       }
  41.       $html .= '</ul>'.PHP_EOL;
  42.     }
  43.     $html .= '</div>'.PHP_EOL;
  44.     return $html;
  45.   } // end function
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement