[英]Hide products only show assigned products to certain user roles in WooCommerce
在我的网上商店 (WooCommerce) 上,我想要一个特定的 function,但我不知道该怎么做。
当您访问该站点时,您可以看到所有没有价格的产品。 作为访问者,您需要与网站所有者联系以获得访问网上商店的帐户。 站点所有者将为仅对具有该特定用户角色的该特定用户可见的产品分配价格。
现在的问题是,当用户使用帐户登录时,他会看到所有产品,即使该产品没有为该特定用户分配价格。
我如何能够在 WooCommerce 内分配产品,当填写价格时,产品将显示给具有特定用户角色的特定用户,并为该特定用户角色设置固定价格?
所以我可以在这个问题中看到 2 个不同的问题。
第一个是“如何只显示属于特定用户角色的产品”
为此,您可能想要更改 woocommerce 产品查询。 您可以通过向主题的functions.php
中添加类似以下代码的内容来实现。php:
function filter_products_by_user_roles( $q ) {
// alter the query only for logged users
if (is_user_logged_in()) {
// get user roles assigned to current profile
$user_meta = get_userdata(get_current_user_id());
$user_roles = $user_meta->roles;
// create new tax_query variable with desired relation
$tax_query = array('relation' => 'OR');
// add a product_tag filter for each user role
foreach ($user_roles as $role) {
$tax_query[] = array(
'taxonomy' => 'product_tag',
'field' => 'slug',
'terms' => $role,
);
}
// overwrite the default tax_query with our custom code
$q->set( 'tax_query', $tax_query );
// set additional attributes for the query
$q->set( 'posts_per_page', '30' );
$q->set( 'post_type', 'product' );
$q->set( 'post_status', 'publish' );
}
}
// hook the alteration to the original product query function
add_action( 'woocommerce_product_query', 'filter_products_by_user_roles' );
此代码将获取所有用户的角色,并将它们 1 1 添加到基于 product_tag 的产品查询过滤器中,这对于此至关重要。 分配的产品标签的 slug 必须与用户角色名称匹配。
例如:用户角色是“VIP_user_2” ,因此分配给所需产品的标签必须是“VIP_user_2”
第二个是“如何为不同的用户角色显示不同的价格”
为此,我们将不得不编辑 woocommerce 个文件,因此首先 go 通过本指南了解如何安全地编辑此类文件: https://woocommerce.com/document/template-structure/
准备好主题后,您可以使用自己的条件和要为用户填写的值/数据库字段编辑 woocommerce/loop/price.php
price.php
中的默认代码是:
<?php if ( $price_html = $product->get_price_html() ) : ?>
<span class="price"><?php echo $price_html; ?></span>
<?php endif; ?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.