如何解决在WooCommerce中使用WC_Query通过作者ID获取产品?
我试图在WooCommerce中使用WC_Query通过帖子作者ID获得产品,因此我尝试在新的自定义meta_key“ _author” 中添加以下内容:
add_filter( 'woocommerce_product_data_store_cpt_get_products_query','handling_custom_meta_query_keys',10,3 );
function handling_custom_meta_query_keys( $wp_query_args,$query_vars ) {
$meta_key = '_author';
if ( ! empty( $query_vars[$meta_key] ) ) {
$wp_query_args['meta_query'][] = array(
'key' => $meta_key,'value' => esc_attr( $query_vars[$meta_key] ),'operator' => '==',);
}
return $wp_query_args;
}
然后我尝试将其与wc_get_products()
一起使用:
$product_list = wc_get_products( array('_author' => get_current_user_id()) );
,但它返回空数组。有想法吗?
解决方法
您可以使用未记录的参数“ author'”简单地通过WC_Query中的作者ID获得产品:
$products = wc_get_products( array(
'status' => 'publish','limit' => -1,'author' => get_current_user_id()
) );
您将获得WC_Product
个对象的数组
您可以像这样使用自定义查询
<?php
$authorID = get_the_author_meta('ID');
$args = array(
'post_type' => 'product','post_status' => 'publish'
'posts_per_page' => 12,'product_cat' => 'pants'
'author' => $authorID
);
$loop = new WP_Query( $args );
?>
<div class="author_products">
<?php if ( $loop->have_posts() ) { ?>
<ul class="author_pubproducts">
<?php while ( $loop->have_posts() ) : $loop->the_post();
woocommerce_get_template_part( 'content','product' );
endwhile; ?>
</ul>
<?php
} else {
echo __( 'No products found','textdomain' );
}
wp_reset_postdata();
?>
希望它能正常工作
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。