mardi 31 mai 2016

Display Last Purchased Products Woocommerce

I am trying to allow a user to display 50 last purchased product in some page so I edited this code: WooCommerce - Recently purchased products

Which is used for the admin to display 5 recent purchased product by all users. But now the issue is that my edited code doesn't display all purchased products for one users, it only displays 4.

This is my edited code:

  // usage: [sold_products max_products="5" title="Les Dérniers Produits Achetés"]
  // 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' => 50, 'title' => "Produis Vendus Récements");
    $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++) {
        if ( is_user_logged_in() ) {
          $user_info = wp_get_current_user();
        }
        $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';
        }
        if($user_info->ID == $user_id){
          $unix_date = strtotime($order->order_date);
          $date = date('d/m/y', $unix_date);
          $html .= '<li><a href="'.$url.'">'.$product_name.'</a> you purchased on '.$date.'</li>'.PHP_EOL;
        }
      }
      $html .= '</ul>'.PHP_EOL;
    }
    $html .= '</div>'.PHP_EOL;
    return $html;
  } // end function

So can someone tell me what's wrong with this code?

Thank you in advanced!



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire