A
A
Anton none2020-04-13 13:15:13
WordPress
Anton none, 2020-04-13 13:15:13

How to get a list of products from certain categories with a certain attribute?

Good afternoon. I'm trying to figure it out, but I can't figure out how to make a query in WP_QUERY with the ability to get an array of products that belong to certain categories (2-3 categories for example) and products in these categories have a certain attribute. In a primitive way, this is to make two selections and remove products without intersection, but this is somehow clearly not correct, maybe there is a possibility to make such a selection with one request ?? I would be extremely grateful for your help!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Dontsov, 2020-04-13
@AndreyBLG

Look at wp-kama site examples of queries - wp_query
Your case is "Category Parameters" and "
Custom Field Parameters" sections And yes, of course, in one query, just use selection parameters together.
Here is an example of a standard loop, pay attention to the $args variable - here you need to describe the selection parameters,

// задаем нужные нам критерии выборки данных из БД

// отберем записи, которые находятся хотя бы в одной из категорий с id 2 или 6 (дочерние категории не будут учитываться)
// и выберем из них записи с ключом поля "color" и значением этого поля = "blue"
$args = array(
  'category__in' => array(2,6),
  'meta_key' => 'color', 'meta_value' => 'blue'
);

$query = new WP_Query( $args );

// Цикл
if ( $query->have_posts() ) {
  while ( $query->have_posts() ) {
    $query->the_post();
    echo '<li>' . get_the_title() . '</li>';
  }
} else {
  // Постов не найдено
}
// Возвращаем оригинальные данные поста. Сбрасываем $post.
wp_reset_postdata();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question