WooCommerce product collection issue - php

I would like to ask how is it possible when i have 3000 variable products in an old woocommerce version eshop, when i am trying to loop throught them that i get only 300 in return instead.
The following code is used by me in order to generate a product feed.
$args = array( 'post_type' => 'product');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
Also the variable products are called variable because they support variation as I understand. That means that 3000 variable products are not 3000 "normal" products and instead the 300 that I see is the correct number of them?

May be you are mixing up products (simple or variable) and product variations (that remain to variable products)... You need to display products (simple and variable) in your WP_Query, but not your product variations.
With 'post_type' => 'product', you will get simple and variable products at the same time.
The missing argument is posts_per_page to be set to -1.
So your code will be:
$args = array( 'post_type' => 'product', 'posts_per_page' => -1);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) :
$loop->the_post();
// set all product IDs in an array
$all_product_ids[] = $loop->post->ID;
endwhile;
// Testing: Output the number of products in that query
echo '<p>Products count: ' . count($all_product_ids) . '</p>';
Then you will get all your products.
May be you can try to use a WPDB query:
## --- THE SQL QUERY --- ##
global $wpdb;
$table_name = $wpdb->prefix . "posts";
$product_ids_array = $wpdb->get_col("
SELECT `ID`
FROM `$table_name`
WHERE `post_status` LIKE 'publish'
AND `post_type` LIKE 'product'
");
## --- TESTING OUTPUT --- ##
// Testing raw output of product IDs
print_r($product_ids_arr);
// Number of products
$products_count = count($product_ids_arr);
echo '<p>Products count: '. $products_count. '</p>';
## --- THE LOOP --- ##
foreach ($product_ids_array as $product_id):
// Get an instance of WP_Product object
$product = new WC_Product($product_id);
// Use the WP_Product methods to get and output the necessary data
endforeach;

Related

Create a shortcode to display related posts (posts in the same category) in the sidebar

I want to display in the article sidebar (in wordpress) a list of 5 recent articles from that category to which it belongs. I'm using the code below to (using a shortcode) show the 5 posts (from category 62 in this case). Is there a way to write this code in functions.php so that it is optimised, and I don't have to rewrite everything for each new category?
/**
* function to add recent posts widget
*/
function wpcat_postsbycategory_musculacao() {
// the query
$the_query = new WP_Query( array( 'cat' => '62', 'posts_per_page' => 5 ) );
// The Loop
if ( $the_query->have_posts() ) {
$string .= '<ul class="postsbytag widget_recent_entries">';
while ( $the_query->have_posts() ) {
$the_query->the_post();
if ( has_post_thumbnail() ) {
$string .= '<li>';
$string .= '' . get_the_post_thumbnail($post_id, array( 80, 80) ) . get_the_title() .'</li>';
} else {
// if no featured image is found
$string .= '<li>' . get_the_title() .'</li>';
}
}
} else {
// no posts found
}
$string .= '</ul>';
return $string;
/* Restore original Post Data */
wp_reset_postdata();
}
// Add a shortcode
add_shortcode('categoryposts-musculacao', 'wpcat_postsbycategory_musculacao');
/**
* function to change search widget placeholder
*/
function db_search_form_placeholder( $html ) {
$html = str_replace( 'placeholder="Pesquisar ', 'placeholder="Buscar ', $html );
return $html;
}
add_filter( 'get_search_form', 'db_search_form_placeholder' );
The complication here is that in WP a post can have multiple categories. You need to decide how to handle that - get from all categories, or if you only want to show posts from one category, how do you choose which?
I've given a few answers below depending on how you want to handle that.
1. Get posts in any of the categories of the current post
As posts can have multiple categories, you can get all of the ids and use this to query for posts that are in any of those categories:
// 1. get the categories for the current post
global $post;
$post_categories = get_the_category( $post->ID );
// 2. Create an array of the ids of all the categories for this post
$categoryids = array();
foreach ($post_categories as $category)
$categoryids[] = $category->term_id;
// 3. use the array of ids in your WP_Query to get posts in any of these categories
$the_query = new WP_Query( array( 'cat' => implode(",",$categoryids), 'posts_per_page' => 5 ) );
1a. Get posts in any of the categories but not their children
Note cat will include children of those category ids. If you want to include those exact categories only and not children, use category__in instead of cat:
$the_query = new WP_Query( array('category__in' => $categoryids, 'posts_per_page' => 5) );
2. Get posts that have all of the categories of the current post
If you want posts that have all the same categories as the current one, this is done in the same way as above, except we use category__and instead of cat (Note that this does not include children of those categories) :
$the_query = new WP_Query( array('category__in' => $categoryids, 'posts_per_page' => 5) );
3. If you know your post will only have one category
If you know you only have one category per post, then you can just use the first element from the category array:
// 1. Just use the id of the first category
$categoryid = $post_categories[0]->term_id;
$the_query = new WP_Query( array( 'cat' => $categoryid, 'posts_per_page' => 5 ) );
4. Pass the category into the shortcode
If you want to specify which category to show, you can pass the category id into the shortcode, letting you choose whichever category you want. (FYI you can also get it to work with slug instead of id, which might be a bit more user-friendly)
Your shortcode is currently used like this, I assume:
[categoryposts-musculacao]
We can change the function so you can pass the category like this:
[categoryposts-musculacao category=62]
Shortcode function can accept an $attributes argument that has the information or "attributes" we're adding to the shortcode, e.g. category. We use this to get the category passed in as a variable called $category and then just use it instead of the hardcoded value in the rest of your function.
// 1. include the $attributes argument
function wpcat_postsbycategory_musculacao( $attributes ) {
// 2. get the value passed in as category - this will save it into a variable called `$category`
extract( shortcode_atts( array(
'category' => ''
), $attributes ) );
// 3. if there is no category don't do anything (or sohw a message or whatever you want
if (!$category) return "";
// 4. Now just use your variable instead of the hardcoded value in the rest of the code
$the_query = new WP_Query( array( 'cat' => $category, 'posts_per_page' => 5 ) );
// do the rest of your stuff!
}
Reference: Wordpress Codex Shortcode API
4a. Pass the category into the shortcode by slug
If you want the category attribute in your shortcode to work with a slug instead of the id, you just need to change WP_Query to use category_name instead of cat:
$the_query = new WP_Query( array( 'category_name' => $category, 'posts_per_page' => 5 ) );

Woocommerce wp_query get order by ID

I am trying to produce a plain output of order data. First step is a WP_QUery (perhaps) so I write this code;
$args = array (
'post_type' =>'shop_order',
'posts_per_page' => -1,
'post_status' => 'any',
//'p' => $post_id,
);
$order_query = new WP_Query( $args );
while ( $order_query->have_posts() ) :
$order_query->the_post();
echo the_ID();
echo ' : ';
the_title();
echo '<br/><br/>';
endwhile;
It obliging products a list of all orders, if I set the 'p' => $post_id where $post_id is a valid post ID, the query returns nothing.
Any idea why, hive mind?
Alternatively is there a Woocommerce way of producing a plain page with a layout like;
Order ID: 836
Order Status: ....
I assumed a WP_Query would be the obvious way but it is appearing like getting woocommerce order data is anything but straightforward.
Update 2
To get the order data for one order, you don't need WP_query. You can use directly:
$order = wc_get_order( $order_id );
$order->id; // order ID
$order->post_title; // order Title
$order->post_status; // order Status
// getting order items
foreach($order->get_items() as $item_id => $item_values){
// Getting the product ID
$product_id = $item_values['product_id'];
// .../...
}
Update 1
You should try this, as with array_keys( wc_get_order_statuses() you will get all order statuses and with 'numberposts' => -1, all existing orders.
Here is an alternative way (without WP_query or you can use thoses args in the WP_query array):
$customer_orders = get_posts( array(
'numberposts' => -1,
'post_type' => 'shop_order',
'post_status' => array_keys( wc_get_order_statuses() )
) );
// Going through each current customer orders
foreach ( $customer_orders as $customer_order ) {
// Getting Order ID, title and status
$order_id = $customer_order->ID;
$order_title = $customer_order->post_title;
$order_status = $customer_order->post_status;
// Displaying Order ID, title and status
echo '<p>Order ID : ' . $order_id . '<br>';
echo 'Order title: ' . $order_title . '<br>';
echo 'Order status: ' . $order_status . '<br>';
// Getting an instance of the order object
$order = wc_get_order( $order_id );
// Going through each current customer order items
foreach($order->get_items() as $item_id => $item_values){
// Getting the product ID
$product_id = $item_values['product_id'];
// displaying the product ID
echo '<p>Product ID: '.$product_id.'</p>';
}
}
The strict answer to this question is change 'p'=>$post_id' to 'post__in' => array($post_id)
...but the real answer, should anyone be treading this path, is that parsing the email is so much easier, woocommerce has done most of the work for you. There are other pratfalls along the way; 1. The post is protected and the order notes are in the excerpt so can't be displayed ( I could move them to meta but...) 2. The order items are within comments and have to be looped then parsed to produce meaningful output, so I might as well parse the email direct.

WooCommerce Custom Loop by Name Instead of Slug

I'm currently showing the products of one WooCommerce product category (events) with the following code:
<?php $args = array( 'post_type' => 'product', 'product_cat' => 'events');
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
Is it possible to get a product category by name instead of slug or ID?
Since I'm using a translation plugin (WPML) slugs have been added per language (for example "events_eng").
Thanks.
You could use another trick is to get the language extension used by WPML in the category slug and then to add it to your slug, this way:
<?php
// Set here your category slug
$cat_slug = 'events';
// Get the current language
$lang = explode("-", get_bloginfo('language'));
// Adding the language extension to the slug
$cat_slug .= '_' . $lang[0];
$args = array( 'post_type' => 'product', 'product_cat' => $cat_slug);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product;
?>
If for the main language you don't have a language extension in the category slug, you can add a condition in this code to avoid adding it to this particular language.
This code is tested and it's fully functional.

Fastest approach: Count all products (including variations) in WooCommerce

I'm wondering if there exist any faster approaches to count all products in WooCommerce (and their child-variations), than this following code-example:
function total_product_count() {
$product_count = 0;
$args = array(
'post_type' => 'product',
'posts_per_page' => -1
);
/* Initialize WP_Query, and retrieve all product-pages */
$loop = new WP_Query($args);
/* Check if array contains any posts */
if ($loop->have_posts()):
while ($loop->have_posts()):
$loop->the_post();
global $product;
/* Count the children - add count to product_count */
product_count += count($product->get_children());
endwhile;
endif;
return $product_count;
}
On my local XAMPP web-server the function executes in 3 seconds (having 253 products), which is way too long time. The function returns 1269.
$product->get_children() is not always correct in this situation. get_children() return child products as well as grouped products if exist.
I hope the better and fastest way is to use wpdb:: MySQL query method. Try the following code
echo 'Number of main products => '.main_product_count();
echo 'Number of variations => '. variation_product_count();
function main_product_count() {
global $wpdb;
$count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE `post_type` LIKE 'product'");
return $count;
}
function variation_product_count() {
global $wpdb;
$count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE `post_type` LIKE 'product_variation'");
return $count;
}
as your naming
$loop =new WP_Query($args);
try this code
$loop->post_count;
while ($loop->have_posts()){
global $product;
/* Count the children - add count to product_count */
$loop->post_count += count($product->get_children());
}
WP_Query has a property which gives you the number of posts found matching the current query parameters:
function total_product_count() {
$args = array( 'post_type' => 'product', 'posts_per_page' => -1 );
$products = new WP_Query( $args );
return $products->found_posts;
}

WooCommerce Display Purchased Items Only

So I have done a bunch of looking around the web and couldn't find a solution for this...
Basically what I am trying to do is display a product loop of all the products the user has purchased in the store just like displaying normal products.
If you still don't understand maybe this will help you get what I mean..
Here is the example product loop on the WooCommerce documentation...
<ul class="products">
<?php
$args = array(
'post_type' => 'product',
'posts_per_page' => 12
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post();
woocommerce_get_template_part( 'content', 'product' );
endwhile;
} else {
echo __( 'No products found' );
}
wp_reset_postdata();
?>
</ul><!--/.products-->
So what if I wanted to display basically this same exact product loop however filter it out so that it only displays products that the user has already purchased.
I honestly do not know where to go with this one and I am sure there are others that have done research on this in the past so maybe this will help out a bunch of people!
Thanks in advance!
There are at least two different approaches you can take to solve this problem.
The first is to get the product from each post, and then get the product ID from each product and then use an if statement to filter using wc_customer_bought_product or woocommerce_customer_bought_product (if you are using old WooCommerece).
The second is to pass the correct arguments to filter the WP_Query to only include orders purchased by a user and then filter products only in those orders. More information on the second approach is available at Get All User Orders and Products bought by user in WooCommerce based shop (archive.org).
An example of the first approach is something like
<!-- code started -->
<ul class="products">
<?php
$user_id = get_current_user_id();
$current_user= wp_get_current_user();
$customer_email = $current_user->email;
$args = array(
'post_type' => 'product',
'posts_per_page' => 12
);
$loop = new WP_Query( $args );
if ( $loop->have_posts() ) {
while ( $loop->have_posts() ) : $loop->the_post(); $_product = get_product( $loop->post->ID );
if (wc_customer_bought_product($customer_email, $user_id,$_product->id)){
woocommerce_get_template_part( 'content', 'product' );
}
endwhile;
} else {
echo __( 'No products found' );
}
wp_reset_postdata();
?>
</ul><!--/.products-->
Kudos to Appleman1234 for providing two answers, both of which will work.
ApppleMan1234's first answer that he provided an example for is to loop through all products and then filter them by calling wc_customer_bought_product(). This certainly will work. If you have n products then you are going to make n+1 database queries.
His second suggestion is a link to a post written by Brajesh Singh who, on June 2, 2013, published a solution on fusedpress.com. The original post is no longer available. I found a cached copy at Google.
Brajesh Singh's solution queries the user's orders, then queries the order details, and last queries the product id in the order item's metadata. This solution then is always only 3 queries. Unless your shop only has 1 or 2 products, this solution is far better.
Here is a slightly edited version of Brajesh Singh's code.
/**
* Get all Products Successfully Ordered by the user
* #return bool|array false if no products otherwise array of product ids
*/
function so28362162_get_all_products_ordered_by_user() {
$orders = so28362162_get_all_user_orders(get_current_user_id(), 'completed');
if(empty($orders)) {
return false;
}
$order_list = '(' . join(',', $orders) . ')';//let us make a list for query
//so, we have all the orders made by this user that were completed.
//we need to find the products in these orders and make sure they are downloadable.
global $wpdb;
$query_select_order_items = "SELECT order_item_id as id FROM {$wpdb->prefix}woocommerce_order_items WHERE order_id IN {$order_list}";
$query_select_product_ids = "SELECT meta_value as product_id FROM {$wpdb->prefix}woocommerce_order_itemmeta WHERE meta_key=%s AND order_item_id IN ($query_select_order_items)";
$products = $wpdb->get_col($wpdb->prepare($query_select_product_ids, '_product_id'));
return $products;
}
/**
* Returns all the orders made by the user
* #param int $user_id
* #param string $status (completed|processing|canceled|on-hold etc)
* #return array of order ids
*/
function so28362162_get_all_user_orders($user_id, $status = 'completed') {
if(!$user_id) {
return false;
}
$args = array(
'numberposts' => -1,
'meta_key' => '_customer_user',
'meta_value' => $user_id,
'post_type' => 'shop_order',
'post_status' => 'publish',
'tax_query' => array(
array(
'taxonomy' => 'shop_order_status',
'field' => 'slug',
'terms' => $status
)
)
);
$posts = get_posts($args);
//get the post ids as order ids
return wp_list_pluck($posts, 'ID');
}
Combining that with a product loop from the question, plus a non-deprecated wc_get_template_part() and an addition of posts_per_page=-1 gives us
<ul class="products">
<?php
$args = array(
'post_type' => 'product',
'post__in' => so28362162_get_all_products_ordered_by_user(),
'posts_per_page' => -1
);
$loop = new WP_Query($args);
if($loop->have_posts()) {
while($loop->have_posts()) : $loop->the_post();
wc_get_template_part('content', 'product');
endwhile;
}
else {
echo __('No products found');
}
wp_reset_postdata();
?>
</ul><!--/.products-->
Not sure if this helps you out at all, but there is a plugin developed by WooThemes to support purchase history.

Categories