Reputation: 406
On my webshop (WooCommerce) I want to have a certain function but I do not know how to do this.
When you visit the site, you can see all the products without the price. As a visitor you will need to get in contact with the site owner to get an account to access the webshop. The site owner will assign prices to the products that are only visible to this specific user with that Specific user role.
Now the problem is, that when the user will login with the account he will see all the products, even if that product has no price assigned to it for this specific user.
How am I able to assign products within WooCommerce, that when the price is filled in, the product will show for that specific user with a specific user role with a fix price set to that specific user role?
Upvotes: 0
Views: 1401
Reputation: 147
So I can see 2 separate issues in this question.
First one being "how to display only products belonging to certain user role"
For this, you might wanna alter the woocommerce product query. You can do so by adding something like the following code to your theme's functions.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' );
This code will take all of the user's roles and add them 1 by 1 to the product query filter based on product_tag, which is essential for this. The slug of assigned product tag must match the user role name.
for example: user role is "VIP_user_2" so the tag assigned to desired products must be "VIP_user_2"
Second one is "How to display different prices for different user roles"
for this, we will have to edit woocommerce files, so first go through this guide on how to safely edit such files: https://woocommerce.com/document/template-structure/
Once your theme is prepared, you can edit the woocommerce/loop/price.php with your own condition and the values / db fields you want to fill in for users
The default code in price.php
is:
<?php if ( $price_html = $product->get_price_html() ) : ?>
<span class="price"><?php echo $price_html; ?></span>
<?php endif; ?>
Upvotes: 1