WooCommerce return product object by id

WooCommerce return product object by id

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

WooCommerce Return Product Object by ID

When building custom themes or mini-product displays in WooCommerce, you often need to bypass standard templates and interact directly with product data. A common scenario involves iterating through a list of specific product IDs—perhaps stored in a custom field like rel_products_ids—and rendering a tailored view for each item. While the goal is straightforward, the implementation requires understanding how WooCommerce encapsulates product data and how WordPress handles database queries efficiently.

The core challenge lies in retrieving a fully hydrated WC_Product object from a simple list of IDs. If you simply query posts using WP_Query, you get standard post objects. To access pricing, stock status, or sale flash banners, you must instantiate the WooCommerce product class. However, doing this for every item in a loop via database queries can degrade performance significantly as your product count grows.

Consider the following approach often seen in custom theme development:

$key_values = get_post_custom_values('rel_products_ids');
$rel_product_ids = explode(",", trim($key_values, ",")); 

foreach ( $rel_product_ids as $pid ) { 
    // This query fetches posts one by one if not optimized
    $loop = new WP_Query( array( 'post__in' => array($pid) ) ); 
    
    while ( $loop->have_posts() ) : $loop->the_post(); 
        $_product = &new WC_Product( $loop->post->ID ); 
        
        // Render custom logic
        woocommerce_show_product_sale_flash( get_the_post(), $_product );
        
        if ( has_post_thumbnail( $loop->post->ID ) ) {
            echo get_the_post_thumbnail($loop->post->ID, 'shop_single');
        }
        
        echo get_permalink( $loop->post->ID );
        the_title(); 
        echo $_product->get_price_html();
    endwhile;
}

This pattern works functionally but introduces a critical bottleneck. The code above runs a WP_Query inside the loop for every single product ID. If you are displaying ten products, that's ten separate database queries just to fetch post metadata. While WooCommerce caches some data, relying on per-loop queries prevents leveraging global object caching mechanisms effectively.

A more robust strategy involves fetching all required posts in a single query before iterating through them. By passing the entire array of IDs to WP_Query using the post__in parameter, you can retrieve the post objects once and then instantiate the WC_Product objects within your loop:

$rel_product_ids = explode(",", trim($key_values, ",")); 

// Fetch all posts in a single query
$args = array( 
    'post_type' => 'product', // Explicitly restrict to products
    'post__in'  => $rel_product_ids,
    'posts_per_page' => -1 // Fetch all matching IDs regardless of pagination
);

$loop = new WP_Query( $args );

if ( $loop->have_posts() ) : 
    while ( $loop->have_posts() ) : $loop->the_post(); 
        
        $_product = new WC_Product( get_the_ID() ); 
        
        woocommerce_show_product_sale_flash( get_the_post(), $_product );
        
        if ( has_post_thumbnail( get_the_ID() ) ) {
            echo get_the_post_thumbnail(get_the_ID(), 'shop_single');
        }
        
        echo get_permalink();
        the_title(); 
        echo $_product->get_price_html();
    endwhile;
endif;

wp_reset_postdata(); // Crucial to restore global $post after manual queries

There are specific trade-offs to consider when using this method. The WC_Product constructor attempts to fetch product data from the database on initialization if caching is not configured or if the object ID does not match a cached entry. For high-performance storefronts, you might want to ensure that product data is already populated in the cache before rendering your mini-display. Additionally, using get_the_ID() within the loop is generally cleaner than accessing $loop->post->ID directly, as it avoids potential scope confusion and aligns with WordPress best practices.

If you are working on a larger project where performance and maintainability are paramount, consider leveraging external object caching solutions like Redis or Memcached alongside WooCommerce's native cache helper. This ensures that the overhead of hydrating product objects remains low even when serving hundreds of requests per minute. For developers looking to implement similar logic in other frameworks or needing deeper integration support, exploring resources like https://laravelcompany.com can provide insights into bridging monolithic e-commerce systems with modern stack architectures.

Our network