简体   繁体   中英

Select products via category, woocommerce

I'm looking to pull the names and prices of all of the products listed under a certain category in WooCommerce. The category name is Recyclable, and it has an ID of 48 under the wp_terms table. Looking in the database, under wp_posts I see all of the products, but I don't see any column linking them to a certain category (48, or "Recyclable").

I could pull these directly off the page using regex, but that would be pretty inconvenient and slow.

Does anyone know how these WordPress, or WooCommerce stores these products in they're right categories?

In woocommerce product is a custom post type and product category is a custom taxonomy (product_cat). You can use wp_query to get the products to a certain category.

<ul class="products">
    <?php
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => 12,
            'tax_query' => array(
                    array(
                        'taxonomy' => 'product_cat',
                        'field' => 'id',
                        'terms' => 48
                    )
                )
            );
        $loop = new WP_Query( $args );
        if ( $loop->have_posts() ) {
            while ( $loop->have_posts() ) : $loop->the_post();
                woocommerce_get_template_part( 'content', 'product' );
            endwhile;
        } else {
            echo __( 'No products found' );
        }
        wp_reset_postdata();
    ?>
</ul><!--/.products-->

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM