0

I want to get all products of category by category name (slug). Сategory has no parents or children. I wrote my code according to this answer. My code:

<?php 
$args = [
    'post_type' => 'product',
    'posts_per_page' => -1,
    'product_cat' => 'pyvo-v-pliashkah'
];

$products = new WP_Query($args);
wp_reset_query();
echo "<pre>";
print_r($products->posts);
?>

But instead products of "pyvo-v-plyashkah" category I get all products of all categoryes. Where is my mistake?

0

The problem with the sample code is that the query is reset before echoing the result.

Instead follow the sample you linked to:

$args = array(
    'post_type' => 'product',
    'posts_per_page' => -1,
    'product_cat' => 'pyvo-v-pliashkah'
);

$products_query = new WP_Query( $args );

// output what you want

wp_reset_query();
  • Thank you, George, but unfortunately result is the same. – Vlad Oct 4 '18 at 6:22
  • Maybe disable all your plugins to make sure it is not a conflict with them. If it then works, you know what to do :) Usually the number of plugins is not so important, it is the code-quality of them which is a factor of keeping them or not. – Pieter Oct 4 '18 at 10:10
0

Try using tax_query

$args = array(
    'posts_per_page' => -1,
    'tax_query' => array(
        array(
            'taxonomy' => 'product_cat',
            'field' => 'slug',
            'terms' => 'pyvo-v-pliashkah'
        )
    ),
    'post_type' => 'product'
);
$the_query = new WP_Query( $args );

Hope it will help!

  • Thank you, Pratik Patel, but the result is the same. Perhaps some plug-in interferes. I have a lot of them)) – Vlad Oct 4 '18 at 7:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.