You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WooCommerce中通过当前产品ID获取更早发布的产品

代码修改方案

如果你的站点使用WordPress 5.8及以上版本,可以直接使用原生post__lt参数筛选ID小于当前产品ID的内容,代码最简洁:

<?php
global $product;
$product_id = $product->get_id();

$args = array(
    'post_type'      => 'product',
    'posts_per_page' => 10,
    'category'       => 15,
    'orderby'        => 'date', 
    'order'          => 'DESC',
    'post_status'    => 'publish', // 仅返回已发布产品,过滤草稿/私有等无效内容
    'post__lt'       => $product_id // 原生参数筛选ID小于当前产品的内容,和你写MySQL查询的逻辑完全一致
);

$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
          wc_get_template_part( 'content', 'older' ); 
endwhile;
// 重置全局文章数据,避免污染页面主循环
wp_reset_postdata();
?>

如果你需要兼容WordPress 5.8以下的低版本,可以通过临时挂载posts_where过滤器实现相同效果:

<?php
global $product, $wpdb;
$product_id = $product->get_id();

// 临时添加ID小于当前产品的查询条件
$id_where = $wpdb->prepare( "AND {$wpdb->posts}.ID < %d", $product_id );
add_filter( 'posts_where', function( $where ) use ($id_where) {
    return $where . $id_where;
}, 99 );

$args = array(
    'post_type'      => 'product',
    'posts_per_page' => 10,
    'category'       => 15,
    'orderby'        => 'date', 
    'order'          => 'DESC',
    'post_status'    => 'publish'
);

$loop = new WP_Query( $args );
// 立即移除过滤器,避免影响页面其他查询逻辑
remove_all_filters( 'posts_where', 99 );

while ( $loop->have_posts() ) : $loop->the_post();
          wc_get_template_part( 'content', 'older' ); 
endwhile;
wp_reset_postdata();
?>

内容的提问来源于stack exchange,提问作者iTommy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 23:54:02