我如何在woocommerce中获得前三个post_id?

时间:2015-11-17 11:49:11

标签: php wordpress woocommerce

如何才能获得与woocommerce类别的产品的前三个ID?

"<?php echo $post->ID; ?>", "<?php echo $post->ID; ?>", "<?php echo $post->ID; ?>"

它仅适用于我的第一个产品ID,我无法获得第二个和第三个产品ID。

你能帮助我吗?

提前谢谢,

最好的问候。

2 个答案:

答案 0 :(得分:1)

您可以使用wordpress的get_posts功能来实现目标。

$args = array(
    'post_type' => 'product',
    'post_status' => 'publish',
    'posts_per_page' => '3',
    'orderby' => 'ID',
    'order' => 'ASC', # Keep ASC for First 3 products or keep DESC for Latest 3 products as required
);
$products = get_posts($args);

foreach($products AS $product){
  echo $product->ID; # You will get different product ids here
}

有关详细信息,请参阅https://developer.wordpress.org/reference/functions/get_posts/

答案 1 :(得分:0)

尝试使用它:

<?php
        $args = array( 'post_type' => 'product', 'posts_per_page' => 3, 'product_cat' => 'your_cat', 'orderby' => 'desc' );
        $loop = new WP_Query( $args );
        while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>

            <div class="product">    

                <a href="<?php echo get_permalink( $loop->post->ID ) ?>" title="<?php echo esc_attr($loop->post->post_title ? $loop->post->post_title : $loop->post->ID); ?>">

                    <h3><?php the_title(); ?></h3>

                    <span class="price"><?php echo $product->get_price_html(); ?></span>                    

                </a>

                <?php woocommerce_template_loop_add_to_cart( $loop->post, $product ); ?>

            </div>

<?php endwhile; ?>
<?php wp_reset_query(); ?>

我希望它对你有用。