Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the wp-statistics domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /home/s/serjpozw/wp-prog.ru/public_html/wp-includes/functions.php on line 6114 Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the cyr2lat domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /home/s/serjpozw/wp-prog.ru/public_html/wp-includes/functions.php on line 6114 Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the essential-addons-for-elementor-lite domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /home/s/serjpozw/wp-prog.ru/public_html/wp-includes/functions.php on line 6114 Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the translatepress-multilingual domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /home/s/serjpozw/wp-prog.ru/public_html/wp-includes/functions.php on line 6114 Notice: Function _load_textdomain_just_in_time was called incorrectly. Translation loading for the wordpress-seo domain was triggered too early. This is usually an indicator for some code in the plugin or theme running too early. Translations should be loaded at the init action or later. Please see Debugging in WordPress for more information. (This message was added in version 6.7.0.) in /home/s/serjpozw/wp-prog.ru/public_html/wp-includes/functions.php on line 6114 Как вывести товары Woocommerce шорткодом - WP-prog

WP-prog

Как вывести товары Woocommerce шорткодом

В этой статье я расскажу о решении, которое позволяет вывести товары Woocommerce кастомным шорткодом по запросу. В самом WC есть свои шорткоды для вывода, но они не всегда подходят, особенно если нам нужно добавить какое-либо произвольное поле.

В шорткоде, который мы создадим, можно указать дополнительные параметры, например, количество выводимых записей. Также наш запрос позволяет сортировать выводимые товары по произвольному полю, созданному с помощью плагина Advanced Custom Fields – одному из наиболее распространенных решений для создания произвольных полей.

Данный код проверен и работает на одном из текущих проектов. В нем есть не только формирование шорткода, но и произвольный запрос. В данном случае он выводит требуемое количество товаров. Т.е. если мы напишем шорткод [esa_lprod per=”5″], то он выведет 5 товаров, если укажем шорткод без параметра, то он выведет 12 товаров, как описано на 6 строке кода.

С 39-й по 53 строку формируется запрос товаров, количество, далее указывается сортировка по ACF полю (acf_date_edu). C 40-й по 50-ю строку мы исключаем из запроса товары, которые находятся в категории “Архивные”.

Далее идет сам цикл, который формирует HTML-верстку и выводит товары.

Шорт-код
				
					<?php 
function esa_list_products($atts)
{
    $params = shortcode_atts(
        array( // в массиве укажите значения параметров по умолчанию
            'per' => '12', // параметр 1
        ),
        $atts
    );

    ob_start();
?>
    <style>
        .lprod {
            display: flex;
        }

        .p_left,
        .p_right,
        .lprod {
            margin: 5px;
        }

        .esa_lp_more {
            padding: 5px 0;
            border: 1px solid #eee;
            text-align: center;
        }

        .p_right {
            width: 350px;
            display: flex;
            flex-direction: column;
        }
    </style>

    <ul class="products">
        <?php
        $args = array(
            'post_type' => 'product',
            'posts_per_page' => $params['per'],
            'meta_key'            => 'acf_date_edu',
            'orderby'            => 'meta_value',
            'order'                => 'ASC',
            'tax_query' => array(
                array(
                    'taxonomy' => 'product_cat',
                    'field' => 'slug',
                    'terms' => array('arhivnye'),
                    'operator' => 'NOT IN'
                )
            )
        );
        $loop = new WP_Query($args);
        if ($loop->have_posts()) {
            while ($loop->have_posts()) : $loop->the_post();

                $categories = get_the_terms($post->ID, 'product_cat'); // получаем категории текущего товара 
                foreach ($categories as $category) {
                    $cat_ids = $category->term_id; // товар может находиться в нескольких категориях 
                }
                $link_page_course = get_field('link_page', "category_" . $cat_ids);
                $date_course = get_field('acf_date_edu');
        ?>
                <li class="lprod">
                    <div class="p_left">
                        <a href="<?= get_permalink($link_page_course[0]); ?>"><?= get_the_post_thumbnail($post = null, array(100, 100)); ?> </a>
                    </div>
                    <div class="p_right">
                        <a class="esa_lp_title" href="<?= get_permalink($link_page_course[0]); ?>"><?= the_title(); ?></a>
                        <?php if ($date_course) {
                            echo '<span>' . __('Дата начала: ' . $date_course, 'woocommerce') . '</span>';
                        } ?>
                        <a class="esa_lp_more" href="<?= get_permalink($link_page_course[0]); ?>"><?= __('Подробнее', 'woocommerce'); ?></a>
                    </div>
                </li>

        <?php endwhile;
        } else {
            echo __('No products found');
        }
        wp_reset_postdata();
        ?>
    </ul>
    <!--/.products-->
<?php
    $output = ob_get_contents(); // всё, что вывели, окажется внутри $output
    ob_end_clean();

    return $output;
}

add_shortcode('esa_lprod', 'esa_list_products');
				
			

Как сформировать запрос товаров Woocommerce и вывести его кастомным шорткодом можно узнать здесь:

О других решениях можно узнать, посетив раздел “Решения” на моем сайте.

Если у Вас есть какие-либо вопросы, оставьте свой комментарий:

2 ответов

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *