在 Woocommerce 的前端仅显示当前用户的产品
Show only current user's products on the frontend in Woocommerce
我只需要在前端显示当前用户的产品,即对于已登录的用户,he/she 应该只能在整个站点上查看他们自己的产品。我尝试了下面的代码,但这限制了对当前用户未创建的所有帖子和页面的访问。我只需要限制 woocommerce 产品。
function shapeSpace_set_only_author($query) {
global $current_user;
$query->set('author', $current_user->ID);
}
add_action('pre_get_posts', 'shapeSpace_set_only_author');
就快完成了,您只需指定您只想更改产品的查询。
add_action( 'pre_get_posts', 'modify_query_show_current_user_products' );
function modify_query_show_current_user_products( $query ) {
global $current_user;
if( ! is_admin() && $query->is_main_query() && isset( $query->query_vars['wc_query'] ) && $query->query_vars['wc_query'] == 'product_query' ) {
$query->set('author', $current_user->ID);
}
}
您可以使用 dedicated woocommerce_product_query
操作挂钩将显示的产品限制为:
add_action( 'woocommerce_product_query', 'shapeSpace_set_only_author', 20, 2 );
function shapeSpace_set_only_author ( $q, $query ) {
if( is_admin() ) return;
global $current_user;
$q->set('author', $current_user->ID);
}
代码进入您活跃的子主题(或主题)的 function.php 文件。
已测试并有效
我只需要在前端显示当前用户的产品,即对于已登录的用户,he/she 应该只能在整个站点上查看他们自己的产品。我尝试了下面的代码,但这限制了对当前用户未创建的所有帖子和页面的访问。我只需要限制 woocommerce 产品。
function shapeSpace_set_only_author($query) {
global $current_user;
$query->set('author', $current_user->ID);
}
add_action('pre_get_posts', 'shapeSpace_set_only_author');
就快完成了,您只需指定您只想更改产品的查询。
add_action( 'pre_get_posts', 'modify_query_show_current_user_products' );
function modify_query_show_current_user_products( $query ) {
global $current_user;
if( ! is_admin() && $query->is_main_query() && isset( $query->query_vars['wc_query'] ) && $query->query_vars['wc_query'] == 'product_query' ) {
$query->set('author', $current_user->ID);
}
}
您可以使用 dedicated woocommerce_product_query
操作挂钩将显示的产品限制为:
add_action( 'woocommerce_product_query', 'shapeSpace_set_only_author', 20, 2 );
function shapeSpace_set_only_author ( $q, $query ) {
if( is_admin() ) return;
global $current_user;
$q->set('author', $current_user->ID);
}
代码进入您活跃的子主题(或主题)的 function.php 文件。
已测试并有效