Created
June 29, 2024 11:05
-
-
Save Acephalia/1cdf72cbfd49dc5c2086e635ddaccba6 to your computer and use it in GitHub Desktop.
Show WooCommerce Price on LearnDash Course Page
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* @snippet Show WooCommerce Price on LearnDash Course Page | |
* @description This code retrieves the WooCommerce price associated with a LearnDash course and displays it on the course page, replacing the default "No Price" label. It also provides a shortcode to manually display the price on any page. | |
* @author u/acephaliax | |
* @source https://insomniainc.com/resources/ | |
* @compatibility Last tested on WooCommerce 9.0.1 | |
* @community r/wordpress, r/woocommerce | |
* @caffeinate https://buymeacoffee.com/acephaliax | |
*/ | |
// Function to get the WooCommerce price associated with a LearnDash course | |
function get_learndash_woocommerce_price($course_id) { | |
// Get all published WooCommerce products | |
$products = wc_get_products(array( | |
'status' => 'publish', | |
'limit' => -1, // Retrieve all products, not just a limited number | |
)); | |
// Loop through each product to find the one associated with the given course | |
foreach ($products as $product) { | |
// Get the related course IDs from the product metadata | |
$course_ids = $product->get_meta('_related_course'); | |
// Check if the course ID is in the array of related course IDs | |
if (is_array($course_ids) && in_array($course_id, $course_ids)) { | |
// If found, retrieve the product price and currency symbol | |
$price = $product->get_price(); | |
$currency_symbol = get_woocommerce_currency_symbol(); | |
// Return the price with the currency symbol | |
return $currency_symbol . $price; | |
} | |
} | |
// If no associated product is found, return an empty string | |
return ''; | |
} | |
// Function to customize the "No Price" label in LearnDash | |
function custom_learndash_no_price_label($label) { | |
// Get the current course ID | |
$course_id = get_the_ID(); | |
// Get the WooCommerce price associated with the course | |
$woo_price = get_learndash_woocommerce_price($course_id); | |
// If a price is found, return it; otherwise, return the original label | |
if (!empty($woo_price)) { | |
return $woo_price; | |
} | |
return $label; | |
} | |
// Add a filter to use the custom "No Price" label in LearnDash | |
add_filter('learndash_no_price_price_label', 'custom_learndash_no_price_label'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Make sure to remove the price from Learndash > Courses > Edit Course > Settings where you want this active.
Support the support: https://buymeacoffee.com/acephaliax