将内容限制为购买Woocommerce产品的用户

时间:2019-08-10 11:48:24

标签: php wordpress woocommerce product shortcode

我正尝试通过短码来限制那些购买特定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 个答案:

答案 0 :(得分:1)

您的代码以及使用简码的方式也存在一些错误

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文件中。经过测试并可以工作。

相关问题