programing

WooCommerce는 속성 쿼리를 통해 제품을 가져옵니다.

lovejava 2023. 3. 15. 17:44

WooCommerce는 속성 쿼리를 통해 제품을 가져옵니다.

아트리뷰트 컬러가 있는 상품이 있습니다.속성 값은 빨강, 파랑 및 초록입니다.커스텀 검색을 작성하려고 하는데 어떤 제품도 꺼낼 수 있는 쿼리를 얻을 수 없습니다.

$args =  array(
    'post_type'      => array('product'),
    'post_status'    => 'publish',
    'posts_per_page' => -1,
    'meta_query'     => array( 
        array(
            'key' => '_visibility',
            'value' => array('catalog', 'visible'),
            'compare' => 'IN',  
        ) 
    ),
    'tax_query'      => array( 
        array(
            'taxonomy'        => 'product',
            'field'           => 'slug',
            'terms'           =>  array('blue', 'red', 'green'),
            'operator'        => 'IN',
        ),
    )
);

$products = new WP_Query( $args );

어디서부터 제가 잘못했을까요?

제품 속성 색상의 올바른 분류법은 입니다.따라서 올바른 작업 쿼리는 다음과 같습니다.

// The query
$products = new WP_Query( array(
   'post_type'      => array('product'),
   'post_status'    => 'publish',
   'posts_per_page' => -1,
   'meta_query'     => array( array(
        'key' => '_visibility',
        'value' => array('catalog', 'visible'),
        'compare' => 'IN',
    ) ),
   'tax_query'      => array( array(
        'taxonomy'        => 'pa_color',
        'field'           => 'slug',
        'terms'           =>  array('blue', 'red', 'green'),
        'operator'        => 'IN',
    ) )
) );

// The Loop
if ( $products->have_posts() ): while ( $products->have_posts() ):
    $products->the_post();
    $product_ids[] = $products->post->ID;
endwhile;
    wp_reset_postdata();
endif;

// TEST: Output the Products IDs
print_r($product_ids);

이 코드는 테스트되어 동작합니다.색상 속성을 가진 모든 제품이 '파란색', '빨간색', '녹색'의 값(용어)을 가지고 있습니다.

WooCommerce 3 이후 제품의 가시성은 커스텀 분류법에 의해 처리됩니다.product_visibility. 다음과 같은 관련 스레드를 볼 수 있습니다.

언급URL : https://stackoverflow.com/questions/45828655/woocommerce-get-products-by-attribute-query