我有一個名為“按日期排序”的帖子的自定義欄位。我希望能夠按創建日期對我的自定義網格進行排序,除非這個自定義的“按日期排序”欄位有一個值......換句話說,如果自定義欄位有一個值,我希望 wordpress 采用該日期并利用它用于分類目的。
現在我將我的變數定義為
$fields['customDate'] = get_field('updated_date', $post->ID);
if (!empty($fields['customDate'])) {
$fields['orderDate'] = $fields['customDate'];
} else {
$fields['orderDate'] = get_the_date('Ymd', $post);
}
為了在頁面上顯示日期,這很好用
<?php echo date('F j, Y', strtotime($fields['orderDate']));?>
對于我的查詢,我有
$posts = get_posts(array(
'post_type' => 'post',
'numberposts' => $numberposts,
'tax_query' => $taxQueries,
'post__not_in' => $exclusions,
'orderby' => array(
'orderDate' => 'DESC'
)
));
但是,我確實意識到,如果我的自定義欄位中沒有資料庫中所有其他帖子的值,這是行不通的。
有沒有辦法通過組合兩個欄位(創建日期和自定義欄位)進行排序,以便如果自定義欄位具有值,則使用它進行排序,如果不使用后創建日期?
提前致謝!
uj5u.com熱心網友回復:
您需要獲取帖子,然后自行對它們進行排序,然后通過post__in引數將其提供給查詢
定義排序函式
function my_sort($a,$b){
$t1 = strtotime($a['date']);
$t2 = strtotime($b['date']);
return $t1 - $t2;
}
獲取所有帖子 ID
$post_ids = get_posts(array(
'fields' => 'ids',
'post_type' => 'post',
'numberposts' => $numberposts,
'tax_query' => $taxQueries,
'post__not_in' => $exclusions,
));
設定陣列以備后用
$get_posts = $post_ids = array();
回圈遍歷 id 并檢查元值是否已設定并存盤在新陣列中
foreach($post_ids as $id){
$updated_date = get_field('updated_date', $id);
$date = $updated_date ? $updated_date : get_the_date('Ymd', $id);
$get_posts[] = array('id' => $id, 'date' => $date );
}
對新的帖子陣列進行排序
usort($get_posts, 'my_sort');
遍歷排序后的陣列并獲取 id
foreach($get_posts as $p ){
$post_ids[] = $p['id'];
}
最后從按我們的排序排序的排序陣列中獲取帖子
$posts = get_post(array(
'posts_per_page' => -1,
'post_type' => 'post',
'post__in' => $post_ids,
'order' => 'DESC',
'orderby'=> 'post__in',
));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/532455.html
