如何从Woo commerce的当前产品ID中获取旧产品



我想从当前的产品id中获得Wooccommerce WordPress中的旧产品,但我看不到任何方法可以将条件添加到数组中(如下所示(。通常,如果我使用Mysql查询,那么我会选择ID<current_ID和按日期订购(Desc(以获得旧产品(旧ID(

有人能支持我编辑此代码以从当前产品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'
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
wc_get_template_part( 'content', 'older' ); 
endwhile;
?>

您可以编写自定义查询来获取当前产品的旧产品。请尝试以下代码。

function get_previous_products( $product_id ){
global $wpdb;
$post_date = get_the_date( 'Y-m-d H:i:s', $product_id );
$get_all_previous_products = $wpdb->prepare( "SELECT p.ID FROM {$wpdb->prefix}posts AS p  WHERE p.post_date > '".$post_date."' AND p.post_type = 'product' ORDER BY p.post_date ASC" );
$get_all_previous_products = $wpdb->get_col( $get_all_previous_products );
return $get_all_previous_products;
}
get_previous_products( $product_id );
function get_next_products( $product_id ){
global $wpdb;
$post_date = get_the_date( 'Y-m-d H:i:s', $product_id );
$get_all_next_products = $wpdb->prepare( "SELECT p.ID FROM {$wpdb->prefix}posts AS p  WHERE p.post_date < '".$post_date."' AND p.post_type = 'product' ORDER BY p.post_date ASC" );
$get_all_next_products = $wpdb->get_col( $get_all_next_products );
return $get_all_next_products;
}
get_next_products( $product_id );

或者,您也可以使用WP_Querydate_query参数。

function get_previous_products( $product_id ){
$get_all_previous_products = new WP_Query(array(
'post_type' => 'product',
'date_query' => array(
array(
'before' => get_the_date( 'Y-m-d H:i:s', $product_id ),
),
),
'fields' => 'ids'
));
return $get_all_previous_products->posts;
}
get_previous_products( $product_id );
function get_next_products( $product_id ){
$get_all_next_products = new WP_Query(array(
'post_type' => 'product',
'date_query' => array(
array(
'after' => get_the_date( 'Y-m-d H:i:s', $product_id ),
),
),
'fields' => 'ids'
));
return $get_all_next_products->posts;
}
get_next_products( $product_id );

最新更新