Home > Blockchain >  How can I get product price, image and perm link by category id woocommerce
How can I get product price, image and perm link by category id woocommerce

Time:08-08

I want to fetch all product title, price,img, permlink by category id. I tried to fetch by category name and I got the product in array but there was no image, price data init.

CodePudding user response:

I think it's what you need. It's the custom WP_Query to get all product data by category id.

$category_id = 10; // replace your category id here
$args = array(
    'post_type'        => 'product',
    'posts_per_page'   => 9, // update your posts_per_page value here
    'post_status'      => 'publish',
    'suppress_filters' => false,
    'tax_query'        => array(
        array(
            'taxonomy' => 'product_cat',
            'terms'    => $category_id,
        ),
    ),
    'fields'           => 'ids'
);

$products_query = new WP_Query($args);
if($products_query->have_posts()){
    foreach($products_query->posts as $product_id){
        $product = wc_get_product($product_id);
        $product_title = get_the_title($product_id);
        $product_image = get_the_post_thumbnail($product_id);
        $product_price = $product->get_price();
        $product_link = get_the_permalink($product_id);
    }
}
  • Related