wordpress代码

产品single页面,如何根据 date 得到下一个产品和上一个产品

<div class="product-navigation">
    <?php
    // 获取上一篇(按日期更早的产品)
    $prev_product = get_adjacent_post( false, '', true, 'catepro');
    pre($prev_product);
    // 获取下一篇(按日期更新的产品)
    $next_product = get_adjacent_post( false, '', false, 'catepro');

    if ($prev_product) {

        // Give the Post Thumbnail a class "alignleft".
        echo get_the_post_thumbnail( $prev_product->ID, 'thumbnail', array( 'class' => 'alignleft' ) );

        echo '<a href="' . get_permalink($prev_product) . '" class="prev-link">← 上一个产品: ' . get_the_title($prev_product) . '</a>';
        echo get_the_thumbnail($prev_product) ;
    }

    if ($next_product) {
        echo '<a href="' . get_permalink($next_product) . '" class="next-link">下一个产品: ' . get_the_title($next_product) . ' →</a>';
    }
    ?>
</div>
      

 

====================

 

或者:

// 获取当前产品的发布时间
$current_date = get_the_date('Y-m-d H:i:s');

// 查询上一个产品(发布时间更早的)
$prev_args = array(
    'post_type' => 'product',
    'posts_per_page' => 1,
    'orderby' => 'date',
    'order' => 'DESC', // 按日期降序(比当前产品早的)
    'date_query' => array(
        array(
            'before' => $current_date,
            'inclusive' => false // 不包含当前产品
        )
    ),
    'post__not_in' => array(get_the_ID()) // 排除当前产品
);
$prev_product = get_posts($prev_args);

// 查询下一个产品(发布时间更新的)
$next_args = array(
    'post_type' => 'product',
    'posts_per_page' => 1,
    'orderby' => 'date',
    'order' => 'ASC', // 按日期升序(比当前产品晚的)
    'date_query' => array(
        array(
            'after' => $current_date,
            'inclusive' => false
        )
    ),
    'post__not_in' => array(get_the_ID())
);
$next_product = get_posts($next_args);

// 输出导航
if (!empty($prev_product)) {
    echo '<a href="' . get_permalink($prev_product[0]->ID) . '" class="prev-link">← 上一个产品: ' . $prev_product[0]->post_title . '</a>';
}

if (!empty($next_product)) {
    echo '<a href="' . get_permalink($next_product[0]->ID) . '" class="next-link">下一个产品: ' . $next_product[0]->post_title . ' →</a>';
}

 

===============

 

或者:

the_post_navigation(array(
    'prev_text' => '<span class="nav-title">← 上一个产品</span>',
    'next_text' => '<span class="nav-title">下一个产品 →</span>',
    'in_same_term' => false, // 不限制分类
    'post_type' => 'product' // 关键:指定自定义类型
));

 

============

或者:

如果产品使用 ​​ACF自定义字段​​(如 release_date)而非原生发布时间:

$adjacent_args = array(
    'post_type' => 'product',
    'orderby' => 'meta_value', // 按字段值排序
    'meta_key' => 'release_date',
    'posts_per_page' => 1,
    'post__not_in' => array(get_the_ID())
);

// 获取上一个产品
$prev_args = array_merge($adjacent_args, array(
    'order' => 'DESC',
    'meta_query' => array(
        array(
            'key' => 'release_date',
            'value' => get_field('release_date'),
            'compare' => '<',
            'type' => 'DATE'
        )
    )
));

========================