How i can restrict portion of post/page content when user bought specific product?
for example:
some content
...
[wcm_restrict product_id="5"]
this content only show for users that bought product 5
[/wcm_restrict]
...
some other content
I tried many plug-ins unfortunately doesn't have this feature. Any help?
How i can restrict portion of post/page content when user bought specific product?
for example:
some content
...
[wcm_restrict product_id="5"]
this content only show for users that bought product 5
[/wcm_restrict]
...
some other content
I tried many plug-ins unfortunately doesn't have this feature. Any help?
Share Improve this question asked Oct 17, 2017 at 9:57 Reza RamezanpourReza Ramezanpour 1311 silver badge6 bronze badges 3- Have you tried to make this shortcode already? This is a good approach, but provide us with the shortcode function to see what might be wrong. – Milan Petrovic Commented Oct 17, 2017 at 10:05
- @MilanPetrovic No, It's just an example. can you suggest a plugin for me? or only possible with code? – Reza Ramezanpour Commented Oct 17, 2017 at 10:14
- I can't give you advice for the plugin, I don't know specifically if some plugin has such shortcode. It would not be too difficult to make the shortcode for this. – Milan Petrovic Commented Oct 17, 2017 at 14:03
2 Answers
Reset to default 2Well, I answering my question.
As @Milan Petrovic mentioned in comments, it's easy to do. just creating shortcode and check if user bought specific product.
Here is the code:
/**
* [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 doesn't bought this product and not an administator
}
// end box
$o .= '</div>';
// return output
return $o;
}
add_shortcode('wcr', 'wcr_shortcode');
Shortcode usage example:
[wcr pid="72"]
This content only show for users that bought product with the id #72
[/wcr]
References
- Shortcodes with Parameters
WooCommerce provides a function to do this.
$current_user = wp_get_current_user();
if ( ! wc_customer_bought_product( $current_user->user_email, $current_user->ID, $product->id ) ) {
_e( 'This content is only visible for users who bought this product.' );
}