Last updated September 8th, 2023 at 12:07 pm
Today, as I prepared to change the price of a membership on one of my MemberPress membership sites, I knew that there are several places on the site where the price of the membership was hard-coded. (For example, I’m displaying a custom pricing table that doesn’t utilize MemberPress Groups Price Box. I also have a callout on the home page which displays the price of this membership — also hard-coded.)
A membership price shortcode would eliminate the need to manually update all those places. However, although MemberPress has lots of shortcodes for content restriction, it doesn’t have one for displaying the price of a membership.
So I created one. Feel free to use this snippet.
Following are two snippets. The first is a bare-bones solution that gets the job done. The second is a bit more fancy.
Bare Bones
/* Gets/Returns price of the membership from postmeta table */ function jdc_get_product_price($mepr_product_id) { return get_post_meta($mepr_product_id, '_mepr_product_price', true); }
/* The Shortcode */ function jdc_shortcode_mepr_product_price($atts) { $atts = shortcode_atts( array( 'id' => '203', ), $atts, 'membership_price' ); $id = $atts['id']; return jdc_get_product_price( $id ); } add_shortcode('membership_price', 'jdc_shortcode_mepr_product_price');
This shortcode displays the price as a number with 2 decimal places and no currency symbol.
- The
id
parameter corresponds to the product ID
A Bit More Fancy
The function that gets and returns the price from the postmeta table is the same as above, as is the add_shortcode()
call.
Here’s the fancier shortcode function (with the return line on separate lines for readability):
/* The Shortcode */ function jdc_shortcode_mepr_product_price($atts) { $atts = shortcode_atts( array( 'id' => '203', 'decimals' => '0', 'sep' => '.', 'thousands' => ',', 'prefix' => '', 'class' => 'price__wrap', ), $atts, 'membership_price' ); $id = $atts['id']; $decimals = $atts['decimals']; $sep = $atts['sep']; $thousands = $atts['thousands']; $prefix = $atts['prefix']; $class = $atts['class']; $price = jdc_get_product_price( $id ); return '<span class="'. $class . '">' . $prefix . number_format($price, $decimals, $sep, $thousands) . '</span>'; } add_shortcode('membership_price', 'jdc_shortcode_mepr_product_price');
This version of the shortcode offers more control. I added a default class of price__wrap
that allows styling with CSS; you could replace that class name with some other to vary how it renders. (The default ‘id’ value is the ID of the membership whose price I changed.)
Example of the shortcode in use:
[membership_price id="999" decimals="2" prefix="$" class="special-price"]
(Of course, you could just enter the currency symbol before the shortcode without having to add the prefix
parameter.)
Leave a Reply