When building out a WooCommerce store, there are often times where you have the slug for a WooCommerce product in your code, and you need to fetch the actual product data such as the permalink, the title or even the ID of the product.
Fetching a product from a slug is not as straight forward as it ought to be, however we have a solution which you can implement in your code.
The solution is two part and will depend on what kind of data you need to retrieve.
Basic WooCommerce Product Data From Slug
If you just require basic data which is specifically not product attribute data, that is set via the WooCommerce product meta box on the Product page in the admin area, then you can use the following snippet.
<?php // Replace `product-slug` with the slug of the product you're fetching. $product = get_page_by_path( 'product-slug', OBJECT, 'product' ); // Example of how to return the product title. if ( ! empty( $product ) ) { echo esc_html( get_the_title( $product ) ); }
If you’re still confused as to what is basic data vs product data, think of basic data as any data that you would usually be able to fetch from a WordPress post, page or custom post type. Things like title, permalink, ID etc.
Advanced WooCommerce Product Data From Slug
Now on to the juicy stuff! If you are wanting product attribute data, such as the sale price or product dimensions, then you will need this snippet.
<?php $product = get_page_by_path( 'wp-most-popular', OBJECT, 'product' ); if ( ! empty( $product ) ) { $product = wc_get_product( $product ); // Example of how to return the sale price if on sale. $price = $product->get_price(); if ( $product->is_on_sale() ) { $price = $product->get_sale_price(); } }
The above snippet fetches the WooCommerce Product Simple Object which allows you to call methods on it to retrieve product data.
We hope these two snippets help you out and as always, don’t be afraid to let us know if you’re getting caught up on anything.
Thanks for the help! Works good.