I’m trying to restrict content on the page via shortcode for those who purchased a particular woocommerce product. I tried using the code below but it’s not working – shortcode [wcr pid="78] this is some text [/wcr]
is just being outputted on the page without hiding the content. Woocommerce has a function for restricting content like this.
/** * [wcr_shortcode description] * @param array pid product id from short code * @return content shortcode content if user bought product */ function wcr_shortcode($atts = [], $content = null, $tag = '') { // normalize attribute keys, lowercase $atts = array_change_key_case((array) $atts, CASE_LOWER); // start output $o = ''; // start box $o .= '<div class="wcr-box">'; $current_user = wp_get_current_user(); if ( current_user_can('administrator') || wc_customer_bought_product($current_user->email, $current_user->ID, $atts['pid'])) { // enclosing tags if (!is_null($content)) { // secure output by executing the_content filter hook on $content $o .= apply_filters('the_content', $content); } } else { // User didn't buy product and not an administator } // end box $o .= '</div>'; // return output return $o; }
Advertisement
Answer
There is some mistakes in your code and in the way to use the shortcode too
1) The code:
add_shortcode( 'wcr', 'wcr_shortcode' ); function wcr_shortcode( $atts, $content = null ){ // Normalize attribute keys, lowercase $atts = array_change_key_case( (array) $atts, CASE_LOWER ); // Shortcode Attributes $atts = shortcode_atts( array( 'pid' => '' ), $atts, 'wcr' ); $user = wp_get_current_user(); // start output $html = '<div class="wcr-box">'; if ( current_user_can('administrator') || wc_customer_bought_product( $user->email, $user->ID, $atts['pid'] ) ) { // enclosing tags if ( ! is_null($content) ) { // secure output by executing the_content filter hook on $content $html .= apply_filters( 'the_content', $content ); } } else { // User hasn't bought this product or is not an administrator $html .= __("Please purchase the product first to see the content", "woocommerce"); } // end box $html .= '</div>'; // return output return $html; }
2) the shortcode usage:
- In a text editor:
[wcr pid="78"] this is some text [/wcr]
. - Inside php code:
echo do_shortcode( '[wcr pid="78"] this is some text [/wcr]' );
.
Code goes in functions.php file of your active child theme (active active theme). Tested and works.