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

标签 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' );

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

最佳答案

您缺少一个 & 符号。应该是&&& 是一个有点明智的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' );

关于php - 如何检查产品是否由 woocommerce 中的用户创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54471018/

相关文章:

php - 从 jQuery 接收 $.post 时索引未定义?

php - 从 php 运行 python 脚本

javascript - 我的提交按钮不起作用

php - Apache 显示 It Works 而不是 WordPress 起始页

php - 尽管有 css 代码,但图像并未显示在整个屏幕上

javascript - 检索 WooCommerce 产品数据并将其传递到 JavaScript 数组

javascript - 通过php加载HTML表单然后使用JQuery提交表单

php - WordPress:显示父菜单标题

javascript - 结帐时出现 WooCommerce JS 问题

php - 检查订单项相关产品是否仍然存在于 WooCommerce 中