Keywords: WooCommerce | Product Price | Custom Shortcode | WordPress Development | PHP Programming
Abstract: This article provides a comprehensive technical guide for displaying WooCommerce product prices by product ID on custom WordPress pages. It analyzes the limitations of existing shortcode solutions and presents a robust approach using the wc_get_product() function to create product objects. The article explains core methods including get_regular_price(), get_sale_price(), and get_price() in detail. Based on best practices, it demonstrates how to create custom shortcodes for flexible price display while avoiding unwanted "Add to Cart" buttons. Through complete code examples and in-depth technical analysis, this guide offers practical solutions for developers.
Problem Background and Technical Challenges
In WordPress website development, there is often a need to display specific WooCommerce product prices on custom pages. While standard WooCommerce shortcodes can show product prices, they typically include "Add to Cart" buttons, which may not be suitable for certain scenarios. Developers require a clean method to retrieve and display only the product price without additional interface elements.
Core Solution: Using WooCommerce Product Objects
WooCommerce provides a robust product object system that allows direct access to product information via product IDs. The key function wc_get_product() is central to solving this problem:
$product_id = 76; // Example product ID
$_product = wc_get_product($product_id);
Once the product object is obtained, various methods can be used to retrieve different types of product prices:
// Get regular price
$regular_price = $_product->get_regular_price();
// Get sale price
$sale_price = $_product->get_sale_price();
// Get current effective price (automatically handles sale logic)
$current_price = $_product->get_price();
Creating Custom Shortcode Implementation
To enable flexible usage within page content, custom shortcodes can be created. This approach allows displaying product prices anywhere using simple shortcode tags:
function custom_price_shortcode_callback($atts) {
$atts = shortcode_atts(array(
'id' => null,
), $atts, 'woocommerce_price');
$html = '';
if (intval($atts['id']) > 0 && function_exists('wc_get_product')) {
$_product = wc_get_product($atts['id']);
$html = "Price: " . $_product->get_price();
}
return $html;
}
add_shortcode('woocommerce_price', 'custom_price_shortcode_callback');
Usage example: Insert [woocommerce_price id="76"] in the post or page editor to display the price of product with ID 76.
Technical Details and Best Practices
Several key technical points require attention during implementation:
Parameter Validation: Use the intval() function to ensure product IDs are valid integers, preventing potential security risks.
Function Existence Check: Employ function_exists('wc_get_product') to verify that the WooCommerce plugin is properly loaded, enhancing code robustness.
Price Formatting: While the example returns raw price values, practical applications can use the wc_price() function for currency formatting:
$formatted_price = wc_price($_product->get_price());
Comparative Analysis with Alternative Methods
Beyond using product object methods, prices can also be retrieved directly via WordPress metadata functions:
// Get regular price
$regular_price = get_post_meta($product_id, '_regular_price', true);
// Get sale price
$sale_price = get_post_meta($product_id, '_sale_price', true);
However, this approach has limitations: it cannot automatically handle sale logic, requiring developers to manually determine which price to display. In contrast, using the product object's get_price() method automatically returns the current effective price (sale price if available, otherwise regular price), making it more intelligent and reliable.
Extended Practical Application Scenarios
This technical solution can be extended to various practical application scenarios:
Product Comparison Pages: Display price information for multiple products on custom comparison pages.
Related Products Display: Show prices of related products on individual product pages, as mentioned in the reference article.
Custom Quotation Systems: Dynamically calculate and display total prices based on user-selected service combinations on service-oriented websites.
Performance Optimization Considerations
Performance optimization becomes crucial when handling large-scale product price displays:
Caching Mechanisms: For product prices that don't change frequently, consider using WordPress Transients API for caching.
Batch Processing: When displaying multiple product prices, avoid repeatedly creating product objects within loops; instead, use batch query methods.
Error Handling and Edge Cases
Various edge cases need to be handled in practical deployments:
function robust_price_shortcode($atts) {
$atts = shortcode_atts(array('id' => null), $atts, 'woocommerce_price');
if (!intval($atts['id']) || !function_exists('wc_get_product')) {
return '';
}
$_product = wc_get_product($atts['id']);
if (!$_product) {
return 'Product not found';
}
$price = $_product->get_price();
if (empty($price)) {
return 'Price not set';
}
return wc_price($price);
}
This robust implementation gracefully handles various exceptional situations such as non-existent products and unset prices.