当我使用自定义帖子类型时,我会收到包含以下代码的下一个链接:
function func_getnextlink() {
global $post;
$html = '';
$next_post = get_next_post();
if($next_post) {
$html .= '<a rel="next" class="next" href="' . get_permalink($next_post->ID) . '">NEXT</a>';
}
return $html;
}
add_shortcode('getnextlink', 'func_getnextlink');
我怎样才能获得下一篇文章,而不是查看我所在的帖子类型? 我应该能够获得两种不同的自定义帖子类型之间的下一个链接。
在活动主题的functions.php文件中添加以下函数
function get_next_post_any_type($current_post_id) {
// Get the current post's publish date
$current_post_date = get_post_field('post_date', $current_post_id);
// Set up the query to find the next post across all post types
$args = array(
'post_type' => 'any', // Get any post type
'posts_per_page' => 1,
'orderby' => 'date',
'order' => 'ASC',
'post_status' => 'publish',
'date_query' => array(
array(
'after' => $current_post_date,
'inclusive' => false,
),
),
);
// Execute the query
$next_post_query = new WP_Query($args);
// Return the post object if found
if ($next_post_query->have_posts()) {
$next_post_query->the_post();
return get_post();
}
// Reset post data
wp_reset_postdata();
// Return null if no post is found
return null;
}
如何使用
$current_post_id = get_the_ID();
$next_post = get_next_post_any_type($current_post_id);
if ($next_post) {
echo 'Next Post Title: ' . $next_post->post_title;
echo 'Next Post URL: ' . get_permalink($next_post->ID);
} else {
echo 'No next post found.';
}