首页 > 解决方案 > Wordpress:我想在 wordpress 的页面上显示所有类别的最新产品?

问题描述

我希望在 wordpress 的页面上显示所有类别中的最新一个产品,当我们在其中添加更多类别和产品时,它应该必须在页面上添加(显示)其单个最新产品。我们该怎么做?请帮我。谢谢

标签: wordpress

解决方案


首先,您需要使用hide_empty.

然后遍历每个类别并为每个类别运行查询以获取单个产品。

$args = array(
    'orderby'    => 'name',
    'order'      => 'ASC',
    'hide_empty' => true
);
$product_categories = get_terms( 'product_cat', $args );
$count = count($product_categories);
if ( $count > 0 ){
    foreach ( $product_categories as $product_category ) {
        echo '<h4><a href="' . get_term_link( $product_category ) . '">' . $product_category->name . '</a></h4>';
        $args = array(
            'posts_per_page' => 1,
            'post_status' => 'publish',
            'post_type' => 'product',
            'tax_query' => array(
                'relation' => 'AND',
                array(
                    'taxonomy' => 'product_cat',
                    'field' => 'slug',
                    'terms' => $product_category->slug
                )
            ),

        );
        $products = new WP_Query( $args );
        echo "<ul>";
        while ( $products->have_posts() ) {
            $products->the_post();
            ?>
                <li>
                    <a href="<?php the_permalink(); ?>">
                        <?php the_title(); ?>
                    </a>
                </li>
            <?php
        }
        wp_reset_postdata();
        echo "</ul>";
    }
}

推荐阅读