How to get product price by id in WooCommerce
In this tutorial we will look into how to get the price of a WooCommerce product by its ID using PHP (PHP price by id), with code examples and you can add this functionality to any WordPress theme.
There are many reasons you might want to get the price of a product by its ID in your WooCommerce store. This can be useful if you have a lot of products and you only want to stock a specific item; or if you’d like to compare prices between two or more products. Whatever your reason, we’re about to find out how to do this!
There are several ways to get the product price in WooCommerce, but we will see how to do that with the help of WooCommerce get product price by id filter. Its purpose is to display the price only for particular product IDs, based on type and quantity filter. This allows you to see in one place the prices of multiple products, eliminating duplicate entries in WooCommerce database.
First we’ll need to have access to the WooCommerce product object. You can create a product object using the following function:
$product = wc_get_product( $post_id );
Once you have access to the product object you will be able to access all product’s data. All available methods can be found here, but the ones you need are:
When you already have a variable containing the WooCommerce product object and you have the product ID for which you need to get the price, it’s very simple. You just have to call one of the WooCommerce methods to get the multiple prices of the product data. The get_regular_price() method will return the product regular price, the get_sale_price() will return the product sale price (discounted price), the get_price() returns the product’s active price and the get_price_html() returns the product price in HTML format.
If you are a developer or a shop manager maybe you want to get product price by id, in this article we have showed you how to get the product price in WooCommerce by using the product identifier. Once you have the product object and the product price of the specific product, you can expand the code and create a custom shortcode to display the price of the product.