WooCommerce Get All Products With No Categories

Hi Guys,

In WooCommerce, you can get all the products with no categories.
If you want to get all products without categories, you can use the following code snippet:

/******Start of the code******/

<?php
include 'wp-load.php';
global $wpdb;
$srNo = 1;
$productWithNoCatsArr = array();
$productIdsResults = $wpdb->get_results("SELECT ID, post_title, post_modified, meta_value as sku FROM " . $wpdb->prefix . "posts as wp left join " . $wpdb->prefix . "postmeta as wpm on wp.ID = wpm.post_id WHERE post_status='publish' AND post_type='product' AND wpm.meta_key='_sku'", ARRAY_A);

foreach ($productIdsResults as $productId) {
$prodId = $productId['ID'];
$product_cats = wp_get_post_terms($prodId, 'product_cat', array("fields" => "ids"));
if (0 == count($product_cats)) {
$productWithNoCatsArr[$prodId]['id'] = $prodId;
$productWithNoCatsArr[$prodId]['name'] = $productId['post_title'];
$productWithNoCatsArr[$prodId]['sku'] = $productId['sku'];
$productWithNoCatsArr[$prodId]['last_updated'] = $productId['post_modified'];
}
}
?>

<h1 class="wp-heading-inline"><?php echo esc_html('Products With No Categories'); ?></h1>
<hr class="wp-header-end"><br>
<table id="products_with_no_categories" cellpadding="5" cellspacing="5" width="100%">
<thead>
<tr>
<th width="3%" style="text-align:center">Sr. No.</th>
<th width="9%" style="text-align:center">Product ID</th>
<th width="15%">SKU</th>
<th width="31%">Product Name</th>
</tr>
</thead>
<tbody>
<?php
if (count($productWithNoCatsArr) > 0) {
foreach ($productWithNoCatsArr as $row) {
$entityID = $row['id'];
$prdName = $row['name'];
$sku = $row['sku'];
?>
<tr>
<td style="text-align:center"><?php echo $srNo; ?></td>
<td style="text-align:center"><?php echo $entityID; ?></td>
<td style="text-align:center"><?php echo $sku; ?></td>
<td><?php echo $prdName; ?></td>
</tr>
<?php
$srNo++;
}
}
?>
</tbody>
</table>

/******End of the code******/

That’s it you are done!

Leave a Reply