Woocommerce get products

前端 未结 4 610
抹茶落季
抹茶落季 2020-12-05 01:30

I used the following code to get the list of product categories form WooCommerce in my WordPress website:

 

        
相关标签:
4条回答
  • 2020-12-05 02:13
    <?php
    $args     = array( 'post_type' => 'product', 'category' => 34, 'posts_per_page' => -1 );
    $products = get_posts( $args ); 
    ?>
    

    This should grab all the products you want, I may have the post type wrong though I can't quite remember what woo-commerce uses for the post type. It will return an array of products

    0 讨论(0)
  • 2020-12-05 02:17

    Do not use WP_Query() or get_posts(). From the WooCommerce doc:

    wc_get_products and WC_Product_Query provide a standard way of retrieving products that is safe to use and will not break due to database changes in future WooCommerce versions. Building custom WP_Queries or database queries is likely to break your code in future versions of WooCommerce as data moves towards custom tables for better performance.

    You can retrieve the products you want like this:

    $args = array(
        'category' => array( 'hoodies' ),
        'orderby'  => 'name',
    );
    $products = wc_get_products( $args );
    

    WooCommerce documentation

    Note: the category argument takes an array of slugs, not IDs.

    0 讨论(0)
  • 2020-12-05 02:28
    <?php  
        $args = array(
            'post_type'      => 'product',
            'posts_per_page' => 10,
            'product_cat'    => 'hoodies'
        );
    
        $loop = new WP_Query( $args );
    
        while ( $loop->have_posts() ) : $loop->the_post();
            global $product;
            echo '<br /><a href="'.get_permalink().'">' . woocommerce_get_product_thumbnail().' '.get_the_title().'</a>';
        endwhile;
    
        wp_reset_query();
    ?>
    

    This will list all product thumbnails and names along with their links to product page. change the category name and posts_per_page as per your requirement.

    0 讨论(0)
  • 2020-12-05 02:36

    Always use tax_query to get posts/products from a particular category or any other taxonomy. You can also get the products using ID/slug of particular taxonomy...

    $the_query = new WP_Query( array(
        'post_type' => 'product',
        'tax_query' => array(
            array (
                'taxonomy' => 'product_cat',
                'field' => 'slug',
                'terms' => 'accessories',
            )
        ),
    ) );
    
    while ( $the_query->have_posts() ) :
        $the_query->the_post();
        the_title(); echo "<br>";
    endwhile;
    
    
    wp_reset_postdata();
    
    0 讨论(0)
提交回复
热议问题