如何通过查询仅检索具有特定 ID 的 WooCommerce 产品?

问题描述 投票:0回答:1

我正在为电子商务网站制作自定义模板。我正在创建一个块来显示多个产品。该产品列表可以通过多种方式排序(例如:随机)。为了划分工作,我创建了一个函数来生成需要显示的 ID 列表。

我创建了一个函数来显示具有此 ID 列表的产品,但它没有使用 ID,原因不明:/(它返回按日期排序的产品):

function displayProducts($product_ids)
{
    $args = array(
        'post_type' => 'product',
        'post__in' => $product_ids,
        'posts_per_page' => count($product_ids),
    );

    $products_query = new WP_Query($args);

    if ($products_query->have_posts()) {
        while ($products_query->have_posts()) {
            $products_query->the_post();
            $product = wc_get_product();

            $product_id = get_the_ID();
            $product_title = get_the_title();
            $image_id = get_post_thumbnail_id($product_id);
            $image_url = wp_get_attachment_image_url($image_id, 'full');
            $categories = get_the_terms($product_id, 'product_cat');
            $artists = wc_get_product_terms($product_id, 'artiste');

            $parts = explode(' – ', $product_title, 2);
            $title = isset($parts[0]) ? $parts[0] : '';

            echo '
            <div class="item">
                <div class="content">
                    <a href="' . get_permalink($product_id) . '">
                        <img src="' . esc_url($image_url) . '" href="' . get_permalink($product_id) . '" alt="' . $product_id . '" />
                    </a>
                    <div class="text">
                        <a href="' . get_permalink($product_id) . '">
                            <h3>' . esc_html($title) . $product_id . '</h3>
                        </a>';

            if ($artists && !empty($artists)) {
                $artist = $artists[0];
                echo '<p>par <a href="' . get_term_link($artist) . '">' . esc_html($artist->name) . '</a></p>';
            }

            if ($categories && !is_wp_error($categories)) {
                $category_links = array();
                echo '<div class="categories">';
                foreach ($categories as $category) {
                    $category_links[] = '<a class="category" href="' . get_term_link($category) . '">' . $category->name . '</a>';
                }
                echo implode(', ', $category_links);
                echo '</div>';
            }

            echo '
                    </div>
                </div>
            </div>';
        }
        wp_reset_postdata();
    }
}
wordpress woocommerce wordpress-theming product advanced-custom-fields
1个回答
0
投票

所以我在 1 天后发现:

$args = array(
    'post_type' => 'product',
    'post__in' => $product_ids,
    'posts_per_page' => count($product_ids),
    'orderby' => 'post__in' // Add this line to maintain order of IDs
);
© www.soinside.com 2019 - 2024. All rights reserved.