[product_category]中定义的简码/woocommerce/includes/class-wc-shortcodes.php是一个很好的起点,尤其是在 Woocommerce 不断发展的情况下!
它的核心只是一个标准的 WP_Query,添加了一些额外的代码来进行分页,从 Woocommerce 设置中设置排序顺序,并检查产品是否标记为可见。
因此,如果您去掉与短代码相关的代码,并想要一个从具有特定 slug 的类别中获取可见产品的函数,它看起来像这样:
function getCategoryProducts($category_slug) {
    // Default Woocommerce ordering args
    $ordering_args = WC()->query->get_catalog_ordering_args();
    $args = array(
            'post_type'             => 'product',
            'post_status'           => 'publish',
            'ignore_sticky_posts'   => 1,
            'orderby'               => $ordering_args['orderby'],
            'order'                 => $ordering_args['order'],
            'posts_per_page'        => '12',
            'meta_query'            => array(
                array(
                    'key'           => '_visibility',
                    'value'         => array('catalog', 'visible'),
                    'compare'       => 'IN'
                )
            ),
            'tax_query'             => array(
                array(
                    'taxonomy'      => 'product_cat',
                    'terms'         => array( esc_attr( $category_slug ) ),
                    'field'         => 'slug',
                    'operator'      => 'IN' // Possible values are 'IN', 'NOT IN', 'AND'.
                )
            )
        );
    if ( isset( $ordering_args['meta_key'] ) ) {
            $args['meta_key'] = $ordering_args['meta_key'];
    }
    $products = new WP_Query($args);
    woocommerce_reset_loop();
    wp_reset_postdata();
    return $products;
}
传入 slug,您将使用您在 Woocommerce 设置中配置的相同顺序返回标准的 wordpress 帖子集合。