кастомный шорт код для вукомертца - есть ошибка, нужна помощь

Может кто-то помочь с кастомным шорт кодом для вукомертца? А точнее, у меня где-то ошибка.

Вывод товаров:

function custom_shortcode_product($atts)
{
    global $woocommerce_loop, $woocommerce;

    extract(shortcode_atts(array(
        'posts_per_page'  => '10',
        'category' => '',
    ), $atts));
    
    $my_posts = get_posts( array(
        'orderby' => 'date',
        'order' => 'desc',
        'post_type'  => 'product',
        'posts_per_page'  => $posts_per_page,
        'category' => $category,
        ) );
    
    ob_start();

        global $post;
    
        foreach( $my_posts as $post ){
            setup_postdata( $post );
        
            woocommerce_get_template_part('content', 'product');
        }
        
        wp_reset_postdata(); // сброс


    return '<div class="woocommerce wrap_spisok_tovar shortcode-product">' . ob_get_clean() . '</div>';
}
add_shortcode('shortcode-product', 'custom_shortcode_product');

Пишу в админке шорт код с параметром категории, не работает, вообще ничего не выводит: [shortcode-product category="150"]

Удаляю строки 'category' => '' и 'category' => $category, выводит все товары.


Ответы (1 шт):

Автор решения: Marina Sorochan

Вам нужна выборка по терму таксономии product_cat. А вы ищете по таксономии для постов обычных - category

function custom_shortcode_product($atts)
{
    global $woocommerce_loop, $woocommerce;

    extract(shortcode_atts(array(
        'posts_per_page'  => '10',
        'category' => '',
    ), $atts));

    $my_posts = get_posts(array(
        'orderby' => 'date',
        'order' => 'desc',
        'post_type'  => 'product',
        'posts_per_page'  => $posts_per_page,
        'tax_query' => [
            [
                'taxonomy' => 'product_cat',
                'field' => 'term_id',
                'terms' => $category,
                'operator' => 'IN'
            ],
        ],

    ));

    ob_start();

    global $post;

    foreach ($my_posts as $post) {
        setup_postdata($post);

        woocommerce_get_template_part('content', 'product');
    }

    wp_reset_postdata(); // сброс


    return '<div class="woocommerce wrap_spisok_tovar shortcode-product">' . ob_get_clean() . '</div>';
}
add_shortcode('shortcode-product', 'custom_shortcode_product');
→ Ссылка