I want to get all the product data in the WooCommerce (product sku, name, price, stock count, availability and etc.) Can I do that using wp-query?
This way you can get all products via wp_query :
global $wpdb;
$all_product_data = $wpdb->get_results("SELECT ID,post_title,post_content,post_author,post_date_gmt FROM `" . $wpdb->prefix . "posts` where post_type='product' and post_status = 'publish'");
And if you want further product data then it will be like this :
$product = wc_get_product($product_id);
$product->product_type;
get_post_meta($prodyct_id, '_regular_price');
$product->get_available_variations();
Thanks for all reply.I have resolve that like billows
$full_product_list = array();
$loop = new WP_Query(array('post_type' => array('product', 'product_variation'), 'posts_per_page' => -1));
while ($loop->have_posts()) : $loop->the_post();
$theid = get_the_ID();
$product = new WC_Product($theid);
if (get_post_type() == 'product_variation') {
// ****************** end error checking *****************
} else {
$sku = get_post_meta($theid, '_sku', true);
$selling_price = get_post_meta($theid, '_sale_price', true);
$regular_price = get_post_meta($theid, '_regular_price', true);
$description=get_the_content();
$thetitle = get_the_title();
}
// add product to array but don't add the parent of product variations
if (!empty($sku))
$full_product_list[] = array("PartyID" => (int) $party_id,"Description"=> $description,
"ExternalNumber" => $theid, "ProductName" => $thetitle, "sku" => $sku,
"RegularPrice" => $regular_price, "SellingPrice" => $selling_price,
"ExternalProductCategoryId" => $cat_id, "ExternalProductCategoryName" => $cat_name);
endwhile;
When your building out your query set the post type to be product
$query->set('post_type', 'product');
And that will only search through woocommerce products.
Also if you are creating a theme, you can take any file from the /wp-content/plugins/woocommerce/templates/ directory and put it inside of /wp-content/themes/<yourTheme>/woocommerce to override any woocommerce page.
you can write this code in page that you want to display all product information
<?php
$args = array(
'post_type' => 'product',
'posts_per_page' => 10
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
echo '<br />' . woocommerce_get_product_thumbnail().' '.get_the_title().'';
global $product;
//echo $product;
echo $product->get_id();
echo $product->get_name();
echo $product->get_sale_price();
echo $product->get_regular_price();
echo $product->get_sku();
echo $product->get_low_stock_amount();
echo $product->get_review_count();
echo $product->get_short_description();
$ratting = $product->get_rating_counts();
for($i = 0 ; $i < count($ratting); $i++) {
echo $ratting[i];
}
endwhile;
wp_reset_query();
?>
This is an old question; the answers using WP_Query() are obsolete since 2018.
See my answer here.
Related
I'm looking to store the results from a WP_query as a $variable and access it outside of the loop. I can only seem to get the first result.
It's is important the $book_data from the results can be accessed outside of the loop.
Code
$args = array(
'post_type' => 'books',
'paged' => $paged,
);
$wp_query = new WP_Query( $args);
$count = $wp_query->post_count;
while ($wp_query->have_posts()) : $wp_query->the_post();
$book_name = get_post_meta( get_the_ID(), 'book_name', true );
$book_author = get_post_meta( get_the_ID(), 'book_author', true );
$book_data = $book_name . ' - ' . $book_author . '<br />';
endwhile;
wp_reset_postdata();
// Access data outside of Loop
echo $book_data;
Current Result
The Stand - Steven King
Desired Result
The Stand - Steven King
War and Peace - Leo Tolstoy
Middlemarch - George Eliot
You're basically overwriting your variable on iteration. You could either a) display the books in the loop, or if as you mentioned you want to use that data in multiple places, you can b) add to an array and display at your discretion.
// Create empty array for book data
$book_data = [];
$args = array(
'post_type' => 'books',
'paged' => $paged,
);
$wp_query = new WP_Query( $args);
$count = $wp_query->post_count;
while ($wp_query->have_posts()) : $wp_query->the_post();
$book_name = get_post_meta( get_the_ID(), 'book_name', true );
$book_author = get_post_meta( get_the_ID(), 'book_author', true );
// Add each book to the array
$book_data[] = $book_name . ' - ' . $book_author;
// can also just echo the above out with:
// echo $book_name . ' - ' . $book_author . '<br />';
endwhile;
wp_reset_postdata();
// Access data outside of Loop
foreach ($book_data as $book) {
echo $book . '</br>;
}
I run mass discounts in a specific category successfully (lets say -50% in category id 123) and everything runs smoothly in product grid, product page and orders. (Wordpress 5.7, Woocommerce: 5.1.0, tried various mass-discount plugins)
However the problem is that when I try to print a list in an admin page through a small plugin I made, I can not get the sale price
I tried:
global $woocommerce;
$args = array('post_type'=>'product','post_status'=>'publish','ignore_sticky_posts'=>1);
$query = new WP_Query( $args );
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) : $query->the_post();
global $product;
$product = wc_get_product( get_the_ID() );
echo $product->get_sale_price()."<br>"; //prints empty
echo $product->get_price()."<br>"; //prints the initial price
echo wc_price( wc_get_price_including_tax( $product ) ).'<br>'; //prints the initial price
echo $product->get_variation_sale_price( 'min', true ).'<br>'; //prints the initial price
if ( $product->is_on_sale() ){
echo 'is on sale<br>'; //it never prints so it does not recognise the product as in sale
}
endwhile;
}
Why is there no sale price? How can I get it? Most products have variations. The product page has the sale price in all products in the category that the sale runs.
You need to query "product" and "product_variation" post type excluding, inside the loop, "variable" product type as follows:
$query = new WP_Query( array(
'post_type' => array('product', 'product_variation'),
'post_status' => 'publish',
'posts_per_page' => -1,
'ignore_sticky_posts' => 1,
) );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) : $query->the_post();
$product = wc_get_product( get_the_ID() );
if ( ! $product->is_type('variable') ){
$active_price = $product->get_price();
$regular_price = $product->get_regular_price();
echo 'Product Id: ' . $product->get_id() . ' <em>(type: ' . $product->get_type() . ')<em><br>';
if ( $product->is_on_sale() {
echo 'Sale price: ' . $active_price . ' <em>(regular price: ' . $regular_price . ')<em><br>';
} else {
echo 'Price: '. $active_price .'<br>';
}
}
endwhile;
}
It should solve your issue.
in woocommerce my-account, i want to show all sells related to a variation attribute. In my case the attribute is the artiste name. I want to show the size/quantity and name of buyer for each order of each product related to the artist. if size is empty, i want to retrieve the variation_sku that contains the size i added.
i started with this function Get all Orders IDs from a product ID in Woocommerce
function retrieve_orders_ids_from_a_product_id( $product_id ) {
global $wpdb;
// Define HERE the orders status to include in <== <== <== <== <== <== <==
$orders_statuses = "'wc-completed'";
//$orders_statuses = "'wc-completed', 'wc-processing', 'wc-on-hold'";
# Get All defined statuses Orders IDs for a defined product ID (or variation ID)
return $wpdb->get_col( "
SELECT DISTINCT woi.order_id
FROM {$wpdb->prefix}woocommerce_order_itemmeta as woim,
{$wpdb->prefix}woocommerce_order_items as woi,
{$wpdb->prefix}posts as p
WHERE woi.order_item_id = woim.order_item_id
AND woi.order_id = p.ID
AND p.post_status IN ( $orders_statuses )
AND woim.meta_key IN ( '_product_id', '_variation_id' )
AND woim.meta_value LIKE '$product_id'
ORDER BY woi.order_item_id DESC"
);
}
The results is pretty good for 90% of cases, except for some orders.
"variation_id" is empty but variation attributes exists but i not able to show them. (like pa_size or variation-sku that contains the size also)
Here is the working code
$artisteTag = "artiste-stack";
$args = array(
'post_type' => 'product',
'posts_per_page' => 99, // dont need pagination
'product_tag' => $artisteTag
);
// Loop for all products with $artistTag related
$loop = new WP_Query( $args );
// how much product do we have
$product_count = $loop->post_count;
// If have products
if( $product_count > 0 )
{
echo "Nombre de Collaborations : ".$product_count."<br>";
echo "<div class='collabs'>";
// for each product show orders related
while ( $loop->have_posts() ) :
$loop->the_post();
global $product;
global $post;
$productID = $product->get_id();
$thePostID = $post->post_title;
$orders_ids_array = retrieve_orders_ids_from_a_product_id( $productID );
// Show "x" orders for "product name" with "cat_name"
echo "<p>Il y a ".count($orders_ids_array)." ventes pour : ".$thePostID." (productID = ".$productID.") - ";
$terms = get_the_terms ( $productID, 'product_cat' );
foreach ( $terms as $term )
{
$cat_id = $term->id;
$cat_name = $term->name;
$cat_slug = $term->slug;
$cat_description = $term->description;
$cat_count = $term->count;
echo $cat_name."</p>";
}
// Loop on the orders
foreach($orders_ids_array as $order_id){
$order = wc_get_order($order_id);
$order_data = $order->get_data();
//var_dump($order_data);
$order_date_created = $order_data['date_created']->date('Y-m-d H:i:s');
$order_billing_first_name = $order_data['billing']['first_name'];
$order_billing_last_name = $order_data['billing']['last_name'];
// show some infos from the order
echo "<div class='order'>";
echo "<p>Commande ".$order_id." faite le ".$order_date_created." par ".$order_billing_first_name." ".$order_billing_last_name."</p>";
echo "<ul>";
foreach ($order->get_items() as $item_key => $item ):
//var_dump($item);
$order_product_id = $item->get_product_id();
$item_name = $item->get_name();
$quantity = $item->get_quantity();
$variation_id = $item->get_variation_id();
// Need something like $variation_sku = $get_variations_sku($product_id);
$variation_size = get_post_meta( $variation_id, 'attribute_pa_taille', true);
// only want to show the product related to the artist and not the total order details
if($order_product_id === $productID )
{
echo "<li>".$item_name." (order_product_id = ".$order_product_id.") (variation_id = ".$variation_id.") Quantité = ".$quantity."</li>";
if ($variation_id)
{
echo $variation_size; // works for 90% of case
}
else
{
// echo $variation_sku;
echo "variation_id is empty but if we show var_dump($item) we can find size in all the data;";
}
}
endforeach;
echo "</ul>";
echo "</div>";
}
endwhile;
echo "</div>";
}
}
}
Any help on where to dig with variation_sku ..didnt find anything on this working.
i find a solution
echo wc_display_item_meta( $item );
will return the good size attribute if variation_id is empty!
I have added a custom post type dropdown to my product categories (see below):
$args = array(
'posts_per_page' => -1,
'post_type' => 'banner',
);
$stickers = get_posts( $args );
echo '<label for="product-banner">Productbanner</label>';
echo '<select name="product-banner" class="product-banner">';
echo '<option value="">Geen banner</option>';
foreach($stickers as $sticker){
echo '<option value="'.$sticker->ID.'">'.get_the_title($sticker->ID).'</option>';
}
echo '</select>';
And to save it:
if ( isset( $_POST['product-banner'] ) ) {
$new_meta_value = $_POST['product-banner'];
$meta_key = 'product-banner';
update_term_meta( $term_id, $meta_key, $new_meta_value );
}
I am showing the sidebar on category pages, and i would like to show the featured image of my selected custom post type dropdown item in there as well.
Is there an easy solution to do this?
Thanks in advance.
EDIT :
$tax_id = get_queried_object()->term_id;
if (get_term_meta($tax_id, 'product-banner', true)) {
$banner_id = get_term_meta($tax_id, 'product-banner', true);
//echo $banner_id;
$banner_post = get_post($banner_id);
$banner_img = get_post_thumbnail_id($banner_post);
echo '<img src="'.wp_get_attachment_image_url( $banner_img, 'full' ).'"style="margin-bottom:-17px;border:1px solid #e8e8e8;" />';
//echo get_queried_object()->term_id;
}
I'm trying to create a simple xml for all my products in my woocommerce.
I already have build most of it, but I simply cant get the current product price in the loop:
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
include_once $path . '/wp-load.php';
header('Content-Type: text/xml; charset=utf-8');
$xml = new SimpleXMLElement('<STORE/>');
$products = $xml->addChild('PRODUCTS');
// Setup your custom query
$args = array(
'post_type' => 'product',
'posts_per_page' => -1
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() && $count<1) {
$count++;
$loop->the_post();
$wcProduct = new WC_Product( get_the_ID() );
$pr = $wcProduct->get_price_html();
$product = $products->addChild('PRODUCT');
$product->addChild('PRODUCT_URL', get_permalink(get_the_ID()));
$product->addChild('PRODUCT_NAME', get_the_title());
$product->addChild('price', $pr);
}
wp_reset_query();
print($xml->asXML());
?>
it gives something relevant, any ideas how to solve it?
$pr = $wcProduct->price; should be all you need in the loop instead of the get_price_html call.