WooCommerce产品权限设置:游客仅看前5个产品的实现方案咨询
WooCommerce: Limit Product Visibility for Guests vs Logged-In Users
Hey there! Let's break down how to implement this "guests see top 5 products, logged-in users see all" functionality for your WooCommerce store.
Your Current Approach: Is It Feasible?
Your core idea of modifying the product query via a hook is totally on the right track, but there are a couple of tweaks needed to make it work reliably:
- The
is_logged_in()check is correct (that's a core WordPress function to verify user authentication), but: - The
$query->set()syntax is off — you can't pass an array directly here. Instead, you need to set theposts_per_pageparameter individually. - You should target the right hook — using
pre_get_postsis a better practice than modifying the theme'sarchive-products.phpdirectly (it keeps your changes theme-independent and easier to maintain).
Revised Custom Code Solution
Here's a polished version of your code that you can add to your theme's functions.php file (or a custom plugin for even better portability):
function limit_guest_product_query( $query ) { // Only target the front-end main WooCommerce product archive query if ( ! is_admin() && $query->is_main_query() && is_shop() ) { // Check if user is NOT logged in if ( ! is_user_logged_in() ) { $query->set( 'posts_per_page', 5 ); // Optional: Sort by "featured" to show your top 5 products $query->set( 'meta_key', '_featured' ); $query->set( 'orderby', 'meta_value_num title' ); $query->set( 'order', 'DESC ASC' ); } } } add_action( 'pre_get_posts', 'limit_guest_product_query' );
What this does:
- Targets only relevant queries: Avoids messing with admin area queries or secondary loops on your site.
- Restricts guest view to 5 products: Logged-in users keep your default (or configured) product per page count.
- Optional sorting: Adds logic to prioritize featured products (adjust the
meta_keyandorderbyif you want to sort by sales, ratings, etc.).
Alternative: Using Plugins
If you'd rather avoid custom code, there are plugins that can handle this kind of content restriction:
- WooCommerce Memberships: Lets you restrict product visibility to logged-in users (or specific membership levels) and offers advanced features like content dripping.
- Free Options: Plugins like "Restrict Content" or "WooCommerce Hide Products" can help limit guest access to product archives, though you might need to tweak settings to only show 5 products to guests.
Important Notes
- Always test custom code on a staging site first before deploying to production.
- If you're using a page builder or custom product archive template, ensure the loop uses the main WordPress query (not a custom loop) for this code to work.
内容的提问来源于stack exchange,提问作者Abid
相关产品推荐
相关产品推荐

