如何检查产品是否由woocommerce中的用户创建

时间:2019-01-31 23:59:06

标签: php wordpress woocommerce

早上好,我正在尝试检查用户是否创建了产品,如果没有,则应删除“添加到购物车”按钮。

我正在一家商店里,注册用户可以从前端创建产品。我添加了此参数以从前端创建产品;

$post = array(
        'post_author' => $currentCOUser_ID // This Return the User's ID using wp_get_current_user()->ID
        'post_status' => "publish",
        'post_excerpt' => $pProduct_excerpt,
        'post_title' => $ProductTitle,
        'post_type' => "product",
    );

    //create product for product ID
    $product_id = wp_insert_post( $post, __('Cannot create product', 'izzycart-function-code') );

创建产品时,我只希望作者和管理员能够在产品单页上看到“添加到购物车”按钮。我使用了下面的代码,但是没有用;

function remove_product_content() {
    global $post;
    $current_user = wp_get_current_user();
    $product_author_id = $current_user->ID;
    $admin_role = in_array( 'administrator', (array) $current_user->roles );


    //check if is a product & user is logged in and is either admin or the author
    //is a product and user is not logged in, remove add to cart
    //is a product and user is logged in and not either admin or product author, remove add to cart button
    if ( is_product() && is_user_logged_in() && (!$admin_role || $product_author_id != $post->post_author)  ) {
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
    }
}
add_action( 'wp', 'remove_product_content' );

当我运行以上代码时,它对所有人完全隐藏了“添加到购物车”按钮。不知道我在做什么错。感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

您缺少一个&符。它应该是&&&是一个明智的AND。有关这两者之间的区别的更多详细信息,请参见此链接:https://stackoverflow.com/a/2376353/10987825

此外,将语句的||部分用括号括起来。否则,只要当前用户不是作者,它将被隐藏。检查这两个链接以查看区别。

Incorrect Version

Correct Version

因此您的代码将变为:

function remove_product_content() {
    global $post;
    $current_user = wp_get_current_user();
    $product_author_id = $current_user->ID;


    //check if is a product & user is logged in and is either admin or the author
    //is a product and user is not logged in, remove add to cart
    //is a product and user is logged in and not either admin or product author, remove add to cart button
    if ( is_product() && (!is_user_logged_in() || (!is_admin() && $product_author_id != $post->post_author)) ) {
        remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 );
    }
}
add_action( 'wp', 'remove_product_content' );