たとえば、イベントの一覧などで、まずは現在進行中、開催前のイベントを日に近い順(日付の和が少ない順)から表示して、その後に今度は終了したイベントを日付の近い順(日付の和が多い順)に表示したいときの件です。
下記のように開催前、開催中 と 開催後 を別々にWp-queryで取得してそれを合体させて表示します。
$args = array(
"post_type" => "event-name",
"posts_per_page" => -1,
'paged' => get_query_var('paged'),
'post_status' => "publish",
'meta_query' => array(
'relation' => 'and',
array(
'key' => 'last_day',
'value' => date('Ymd'),
'compare' => ">=", // Compare operator for date values
'type' => 'DATE', // Type of data being compared
),
),
'meta_key' => 'last_day',
'orderby' => 'meta_value',
'order' => 'ASC'
);
$args2 = array(
"post_type" => "event-name",
"posts_per_page" => -1,
'paged' => get_query_var('paged'),
'post_status' => "publish",
'meta_query' => array(
'relation' => 'and',
array(
'key' => 'last_day',
'value' => date('Ymd'),
'compare' => "<", // Compare operator for date values
'type' => 'DATE', // Type of data being compared
),
),
'meta_key' => 'last_day',
'orderby' => 'meta_value',
'order' => 'DESC'
);
$query1 = new WP_Query($args);
$query2 = new WP_Query($args2);
$merged_results = array_merge($query1->posts, $query2->posts);
$total_posts = count($merged_results);
$posts_per_page = $number;
$total_pages = ceil($total_posts / $posts_per_page);
$current_page = get_query_var('paged') ? get_query_var('paged') : 1;
$offset = ($current_page - 1) * $posts_per_page;
$paginated_results = array_slice($merged_results, $offset, $posts_per_page);
foreach ($paginated_results as $post) {
// Display your post content here
setup_postdata($post);
$post_id = $post->ID;
$ret .= get_the_title($post_id);
}
wp_reset_query();
$ret .= '</div>';
if ($pagination) {
$ret .= pagination($total_pages);
}
echo $ret;
ここで関数paginationは下記です
function pagination($pages = '', $range = 4)
{
$ret = "";
$showitems = ($range * 2) + 1;
global $paged;
if (empty($paged)) $paged = 1;
if ($pages == '') {
global $wp_query;
$pages = $wp_query->max_num_pages;
if (!$pages) {
$pages = 1;
}
}
if (1 != $pages) {
$ret .= "<div class=\"post_pagination\">";
$ret .= "<div class=\"post_pagination__body\">";
if ($paged > 2 && $paged > $range + 1 && $showitems < $pages) $ret .= "<a href='" . get_pagenum_link(1) . "#anchor_target'>« 最初</a>";
if ($paged > 1 && $showitems < $pages) $ret .= "<a href='" . get_pagenum_link($paged - 1) . "#anchor_target'>‹ 前</a>";
for ($i = 1; $i <= $pages; $i++) {
if (1 != $pages && (!($i >= $paged + $range + 1 || $i <= $paged - $range - 1) || $pages <= $showitems)) {
$ret .= ($paged == $i) ? "<span class=\"current\">" . $i . "</span>" : "<a href='" . get_pagenum_link($i) . "#anchor_target' class=\"inactive\">" . $i . "</a>";
}
}
if ($paged < $pages && $showitems < $pages) $ret .= "<a href=\"" . get_pagenum_link($paged + 1) . "#anchor_target \">次 ›</a>";
if ($paged < $pages - 1 && $paged + $range - 1 < $pages && $showitems < $pages) $ret .= "<a href='" . get_pagenum_link($pages) . "#anchor_target'>最後 »</a>";
$ret .= "</div>\n";
$ret .= "</div>\n";
}
return $ret;
}