将内容限制为购买了 Woocommerce 产品的人

Restrict content to those who purchased a Woocommerce product

我正在尝试通过短代码限制页面上的内容,以供那些购买了特定 woocommerce 产品的人使用。我尝试使用下面的代码,但它不起作用 - 短代码 [wcr pid="78] this is some text [/wcr] 只是在页面上输出而没有隐藏内容。 Woocommerce 有一个 function 用于限制这样的内容。

/**
 * [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;
}

您的代码和使用短代码的方式也有一些错误

1) 代码:

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) 简码用法:

  • 在文本编辑器中:[wcr pid="78"] this is some text [/wcr]
  • 内 php 代码:echo do_shortcode( '[wcr pid="78"] this is some text [/wcr]' );.

代码进入您的活动子主题(活动活动主题)的 functions.php 文件。 已测试并有效。