0
我如何才能獲得前三個ID只有與woocommerce類別的產品?我如何獲得woocommerce中的前三個post_id?
"<?php echo $post->ID; ?>", "<?php echo $post->ID; ?>", "<?php echo $post->ID; ?>"
它只適用於我的第一個產品ID,我無法獲得第二個和第三個產品ID。
你能幫我嗎?
預先致謝,
此致敬意。
我如何才能獲得前三個ID只有與woocommerce類別的產品?我如何獲得woocommerce中的前三個post_id?
"<?php echo $post->ID; ?>", "<?php echo $post->ID; ?>", "<?php echo $post->ID; ?>"
它只適用於我的第一個產品ID,我無法獲得第二個和第三個產品ID。
你能幫我嗎?
預先致謝,
此致敬意。
您可以使用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/
嘗試使用此:
<?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(); ?>
我希望它會爲你工作。
是什麼$崗位包含哪些內容? – Lino
你要從哪裏拉他們?您需要創建一個查詢,返回一組您可以在一段代碼中循環的帖子。您不會像上面所做的那樣手動將它們創建爲內聯代碼段。雖然你可以,但在這種情況下你會明確地設置所需的ID。 (但是,再次,幾乎沒有必要這樣做) – Madivad