WooCommerce get all products with SKU - wordpress

I want to get a list of products with sku and post id with this code, everything seems fine and ok with this code :
$statuses = array('publish', 'draft');
// Args on the main query for WC_Product_Query
$args = [
'status' => $statuses,
'orderby' => 'name',
'order' => 'ASC',
'limit' => -1,
];
$vendor_products = wc_get_products($args);
$list_array = array();
foreach ($vendor_products as $key => $product) {
if ($product->get_type() == "variable") {
// Args on product variations query for a variable product using a WP_Query
$args2 = array(
'post_parent' => $product->get_id(),
'post_type' => 'product_variation',
'orderby' => array( 'menu_order' => 'ASC', 'ID' => 'ASC' ),
'fields' => 'ids',
'numberposts' => -1,
);
foreach ( get_posts( $args2 ) as $child_id ) {
// get an instance of the WC_Variation_product Object
$variation = wc_get_product( $child_id );
if ( ! $variation || ! $variation->exists() ) {
continue;
}
$list_array[] = array(
'sku' => $variation->get_sku(),
'postid' => $variation->get_id()
);
}
} else {
$list_array[] = array(
'sku' => $product->get_sku(),
'postid' => $product->get_id()
);
}
}
I have total 1660 (470 published and 1,190 drafted) products but it's just returns 501 products and i don't know why!
this is my products in woocommerce:
this is the final result of query :
this is the result of Janki's code

// Woocommerce get all products
$args = array(
'post_type' => array('product','product_variation'),
'meta_key' => '_sku',
'post_status' => array('publish','draft'),
'meta_query' => array(
array(
'key' => '_sku',
'compare' => 'EXISTS',
),
),
);
$products = new WP_Query($args);
/* using this code you can get all products */
/* this may help you to get details */

Related

Wordpress WP_Query, exclude date from meta term

I'm making an API using WP-JSON for a client, they're using a plugin that manage events and the API should return next events, not the past.
function app_get_newer_posts($data) {
$args = array(
'post_type' => 'event',
'post_status' => 'publish',
'posts_per_page' => 99,
'paged' => $data['page'],
'meta_key' => 'ovaem_date_start_time',
'orderby' => 'meta_value_num',
'order' => 'asc'
);
$query = new WP_Query( $args );
if ($query->have_posts()) {
$ret = [];
while ( $query->have_posts() ) {
$term = get_term(get_the_ID,'');
$query->the_post();
setlocale(LC_TIME, 'it_IT.UTF8', 'it.UTF8', 'it_IT.UTF-8', 'it.UTF-8');
if(get_post_meta(get_the_ID(), 'ovaem_date_start_time')[0] < date("Y-m-d")) {
$ret['schedule'][] = [
'date' => strftime('%e %B %Y',get_post_meta(get_the_ID(), 'ovaem_date_start_time')[0]),
'category' => [ get_the_terms( get_the_ID(), 'categorie' )[0]->name ],
'premium' => false,
'url' => get_the_permalink(),
'groups' => [[
'time' => utf8_encode( strftime("%d %b %Y", get_post_meta(get_the_ID(), 'ovaem_date_start_time')[0]) ),
'sessions' => [[
'id' => get_the_ID(),
'name' => html_entity_decode(the_title('','',false), ENT_QUOTES),
'location' => get_the_terms( get_the_ID(), 'location')[0]->name,
'description' => get_the_content(),
'timeStart' => date('d M Y h:i',get_post_meta(get_the_ID(), 'ovaem_date_start_time')[0]),
'timeEnd' => date('d M Y h:i',get_post_meta(get_the_ID(), 'ovaem_date_end_time')[0]),
'categories' => [ get_the_terms( get_the_ID(), 'categorie' )[0]->name ],
'pic' => get_the_post_thumbnail_url(),
'position' => [
'lat' => get_post_meta(get_the_ID(), 'ovaem_event_map_lat')[0],
'lng' => get_post_meta(get_the_ID(), 'ovaem_event_map_lng')[0]],
'slug' => get_post_field( 'post_name', get_post() ),
]]
]]
];
}
}
} else {
$ret = "-1";
}
return $ret;
}
At the moment, it get all the posts of type event and order by meta_key "ovaem_date_start_time", but it should exclude all the past events.
What parameter should I pass to the args array to compare current meta_key value to today date?
'meta_query' => array(
array(
'key' => 'ovaem_date_start_time',
'value' => time(),
'compare' => '>=',
)
)
Would something like this work, getting all events where the start date is greater than the current date, you may need to change the value as it depends what ovaem_date_start_time is actually saved as whether its time or datetime

Check if a Category contains any products that are on sale in WooCommerce?

Well, it may sound easy but I searched a lot but could not find the appropriate answer. I want to check if a category contains any sale products.
For example, there are 10 categories. I want to get categories that contain products with sale and exclude those categories that don't contain any sale items.
Well, I am new to WP.
I searched a lot about the solution and finally I managed to write my own logic for answering this.
Steps:
Get all categories
Get all ids of sale products
loop through categories of step 1
get products id of this category
loop through ids of ids of step 4
check if that id is present in list of ids of sale product
if found, set flag to true and exit
if flag is false (no product on sale), unset the category
Here is my sample code:
<?php
$args = array(
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => true,
'parent' => 0,
);
$categories = get_terms( 'product_cat', $args );
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$query_args = array(
'post_status' => 'publish',
'post_type' => 'product',
'posts_per_page' => -1,
'paged' => $paged,
'orderby' => 'ASC',
'meta_query' => WC()->query->get_meta_query(),
'post__in' => array_merge( array( 0 ), wc_get_product_ids_on_sale() )
);
$sale_products = new WP_Query( $query_args );
$products_ids_on_sale = wc_get_product_ids_on_sale();
if($sale_products->have_posts()) {
foreach ($categories as $key => $category) {
//get product ids
$category_product_ids = get_posts( array(
'post_type' => 'product',
'posts_per_page' => -1,
'post_status' => 'publish',
'fields' => 'ids',
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $category->term_id,
'operator' => 'IN',
)
),
) );
$is_product_exist = false;
if ( ! empty($category_product_ids) ) {
foreach ($category_product_ids as $product_id) {
if (in_array($product_id, $products_ids_on_sale)) {
$is_product_exist = true;
break;
}
}
if ( $is_product_exist === false ) {
unset($categories[$key]);
}
}
}
wp_reset_query();
}
I have written a article on my blog and explain in more detail about the produces and code at https://www.kodementor.com/get-only-categories-that-contain-products-on-sale/
This code display only on sale product in your store.
Please add below code in your active theme functions.php file
add_action( 'woocommerce_product_query', 'only_sale_product_in_store' );
function only_sale_product_in_store( $q ){
$product_ids_on_sale = wc_get_product_ids_on_sale();
$q->set( 'post__in', $product_ids_on_sale );
}
May is useful for you. Thanks

custom wp_query where meta_key is variable or not needed

To make a custom post type filterable and sortable, i created a custom query that works based on variables in url, accessed by $_GET.
One specific situation breaks it. This is an (un)specified metakey. In the case of sort, the metakey is needed when sorting on a custom field. In the other cases, the metakey can be ignored. However, when i set the variable on empty, the query doesnt produce any posts. How to deal with an empty meta_key?
So far i tried to set the variable as empty ($variable ='');
I set the variable as null; I have used unset.
if (isset($_GET["key"]) || isset($_GET["orderby"])){
if (isset($_GET["key"])) {$key = $_GET["key"];}
else {$key = '';}
if (isset($_GET["value"])) {$value = $_GET["value"]; echo $value;}
else {$value = '';}
if (isset($_GET["orderby"])) {$orderby = $_GET["orderby"];}
if ($orderby='meta_value'){$meta_key='averagerating';}
else {$orderby='';$meta_key='';}
if (isset($_GET["order"])) {$order = $_GET["order"];}
else {$order='';}
$cat = get_queried_object();
if (!empty($cat) && !is_post_type_archive('bedrijf')){
$category = $cat->name;
}
if (is_post_type_archive('bedrijf')){
$category = '';
$terms = get_terms( 'bedrijfs-category' );
// convert array of term objects to array of term IDs
$category = wp_list_pluck( $terms, 'name' );
}
global $post;
$the_query ='';
$args = array(
'post_type' => 'bedrijf',
'posts_per_page' => 10,
'meta_key' => ''.$meta_key.'',
'orderby' => ''.$orderby.'',
'order' => ''.$order.'',
'tax_query' => array(
array(
'taxonomy' => 'bedrijfs-category',
'field' => 'name',
'terms' => $category
)
),
'meta_query' => array(
array(
'key'=> ''.$key.'',
'value' => ''.$value.'',
'compare' => 'LIKE'
)
)
);
$the_query = new WP_Query($args); }
WHat i would like is a solution for inserting an empty variable in the meta_key => ''.$meta_key.'' so the loop skips the meta_key part.
define meta_query or tax_query out of $args
and (example):
if($_GET['some_name'] !== ''){
$meta_query = array(
array(
'taxonomy' => 'bedrijfs-category',
'field' => 'name',
'terms' => $category
)
);
//define args with some_one para exists
$args = array(
'post_type' => 'bedrijf',
'posts_per_page' => 10,
'meta_key' => ''.$meta_key.'',
'orderby' => ''.$orderby.'',
'order' => ''.$order.'',
'meta_query' => $meta_query
);
}else{
//define args with some_one para not exists
$args = array(
'post_type' => 'bedrijf',
'posts_per_page' => 10,
'meta_key' => ''.$meta_key.'',
'orderby' => ''.$orderby.'',
'order' => ''.$order.''
);
}
tax_query is like this

Woo-Commerce Product Query with Multiple Arguments

I am trying to Query Woo-Commerce products based on the following
Featured
Popular
Promotional
Free
I was working to show them in isotop so I have to get all products and give specifiq tag based on my query to make filter. I was confused if I can make 4 Query as I have 4 different arguments / parameter.
I made 4 different query and got result in 4 different array. But there have problems.
I had done 4 Queries and Save result on 4 array. So there same products containing. I have to filter all products and if same product in more than one category I have to input tag like features free . as Isotop works.
If I unique marge array it will not show products in multiple category. But same products can be in two categories or can be in all categories so it should add tag in duplicate product and clear duplicate products list so that in result there will be unique product with multi tag.
Any idea how to do that ?
Below is my code which providing all products.
<?php
foreach ($filter_attr as $item) {
if ($item == 'featured') {
$meta_query = WC()->query->get_meta_query();
$tax_query = WC()->query->get_tax_query();
$tax_query[] = array(
'taxonomy' => 'product_visibility',
'field' => 'name',
'terms' => 'featured',
'operator' => 'IN',
);
$query_args = array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'posts_per_page' => '12',
'orderby' => 'date',
'order' => 'desc',
'meta_query' => $meta_query,
'tax_query' => $tax_query,
);
$loop = new WP_Query($query_args);
if ($loop->have_posts()) {
while ($loop->have_posts()) : $loop->the_post();
$featured_product = array(
"type"=>$item,
"product" => get_the_ID(),
);
endwhile;
} else {
echo __('No products found');
}
wp_reset_postdata();
} elseif($item == 'popular'){
$query_args = array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'posts_per_page' => '12',
'meta_key' => 'total_sales',
'orderby' => 'meta_value_num'
);
$loop = new WP_Query($query_args);
if ($loop->have_posts()) {
while ($loop->have_posts()) : $loop->the_post();
$id=array();
$popular_product = array(
"type"=>$item,
"product" => get_the_ID(),
);
print_r($popular_product);
endwhile;
} else {
echo __('No products found');
}
wp_reset_postdata();
} elseif($item == 'promotional'){
$query_args = array(
'posts_per_page' => 12,
'post_type' => 'product',
'meta_key' => '_sale_price',
'meta_value' => '0',
'meta_compare' => '>='
);
$loop = new WP_Query($query_args);
if ($loop->have_posts()) {
while ($loop->have_posts()) : $loop->the_post();
$id=array();
$promotional_product = array(
"type"=>$item,
"product" => get_the_ID(),
);
print_r($promotional_product);
endwhile;
} else {
echo __('No products found');
}
wp_reset_postdata();
} elseif($item == 'freebies'){
$query_args = array(
'posts_per_page' => 12,
'post_type' => array('product', 'product_variation'),
'meta_query' => array(
array(
'key' => '_price',
'value' => 0,
'compare' => '<=',
'type' => 'NUMERIC'
)
)
);
$loop = new WP_Query($query_args);
if ($loop->have_posts()) {
while ($loop->have_posts()) : $loop->the_post();
$id=array();
$freebies_product = array(
"type"=>$item,
"product" => get_the_ID(),
);
print_r($freebies_product);
endwhile;
} else {
echo __('No products found');
}
wp_reset_postdata();
}
}
?>

how to add another list parameter for meta_query

here is my wordpress new query loop $args
if (isset($_GET['list_shows'])) {
if ($_GET['list_shows'] == 'update') {
$orderby = 'modified';
$order = '';
} elseif ($_GET['list_shows'] == 'views') {
$orderby = 'meta_value_num';
$order = 'DESC';
} elseif ($_GET['list_shows'] == 'popularity') {
$orderby = 'comment_count';
$order = 'DESC';
}
} else {
$orderby = 'modified';
$order = '';
}
$argz=array(
'posts_per_page' => '-1',
'orderby'=>$orderby,
'order'=>$order,
'meta_query' => array(
array(
'key' => 'fragman',
'compare' => 'NOT EXISTS',
'posts_per_page' => '-1',
)
),
'date_query' => array(
array(
'column' => 'post_date_gmt',
'after' => '2 days ago',
),
'posts_per_page' => '-1',
),
);
the question is about ordering posts by meta_value_num , descending ?
my post views meta key = views, could we add this ordering parameter in this meta query ?
if it is, how can we do it. ?
Thanks.
You can pass like this
global $wp_query;
$args = array(
'meta_key' => 'views',
'orderby' => 'meta_value meta_value_num',
'order' => 'DESC'
);
query_posts( array_merge( $args , $wp_query->query ) );
I hope this will work for you.

Resources