How can I retrieve only WooCommerce products with specific IDs through a query?
How can I retrieve only WooCommerce products with specific IDs through a query?
I am making a custom template for an e-commerce website. I am creating a block to display multiple products. This list of product can be sorted in various ways (ex: random). To divide the work I made a function that generates a list of IDs that need to be displayed.
I created a function to display the product with this list of IDs, but it doesn't use the IDs for an obscure reason :/ (it returns products sorted by date):
function displayProducts($product_ids)
{
$args = array(
'post_type' => 'product',
'post__in' => $product_ids,
'posts_per_page' => count($product_ids),
);
$products_query = new WP_Query($args);
if ($products_query->have_posts()) {
while ($products_query->have_posts()) {
$products_query->the_post();
$product = wc_get_product();
$product_id = get_the_ID();
$product_title = get_the_title();
$image_id = get_post_thumbnail_id($product_id);
$image_url = wp_get_attachment_image_url($image_id, 'full');
$categories = get_the_terms($product_id, 'product_cat');
$artists = wc_get_product_terms($product_id, 'artiste');
$parts = explode(' – ', $product_title, 2);
$title = isset($parts[0]) ? $parts[0] : '';
echo '
<div class="item">
<div class="content">
<a href="' . get_permalink($product_id) . '">
<img src="' . esc_url($image_url) . '" href="' . get_permalink($product_id) . '" alt="' . $product_id . '" />
</a>
<div class="text">
<a href="' . get_permalink($product_id) . '">
<h3>' . esc_html($title) . $product_id . '</h3>
</a>';
if ($artists && !empty($artists)) {
$artist = $artists[0];
echo '<p>par <a href="' . get_term_link($artist) . '">' . esc_html($artist->name) . '</a></p>';
}
if ($categories && !is_wp_error($categories)) {
$category_links = array();
echo '<div class="categories">';
foreach ($categories as $category) {
$category_links[] = '<a class="category" href="' . get_term_link($category) . '">' . $category->name . '</a>';
}
echo implode(', ', $category_links);
echo '</div>';
}
echo '
</div>
</div>
</div>';
}
wp_reset_postdata();
}
}
Turbo Multi-language Translator
Make the better internet purchasing globaly
Turbosify SEO Speed Booster
5.0 (7)•Free plan available
Get better conversions by improving store loading speed
Installed
Turbo Multi-language Chat - AI Customer service in one hand