問題描述

我正在使用自定義分類術語頁面模板,其中我們希望連接到按出版日期 (自定義日期字段) 排序的術語的項目 – 如果同一天有多個項目 (格式如 YYYY-MM-DD),則按標題排序,如果自定義字段尚未填寫 (較舊的項目),最後按標題排序。

所以,我用 WP_query 嘗試了一百種不同的方式,它確實會返回大部分結果,因為我想要它們 – 但是在這種情況下,它只返回具有 publication_date 的 meta_key 的項目。所有其他項目都被忽略,不顯示。我使用”or” 的關係嘗試了一個 meta_query,並將 publication_date 作為 EXISTS 和 NOT EXISTS 進行比較,但是對我來説返回了 0 個結果。

此外,該站點運行 3.5.2 仍然,他們不想升級。

這是我最近的一個查詢,讓我看到以正確順序顯示 publication_date 自定義字段的帖子:

$term = get_queried_object(); // find the term of the taxonomy page we are on
$wp_query = new WP_Query( array(
'post_type' => 'resource',
'tax_query' => array(
    array(
        'taxonomy' => 'resource_types',
        'field' => 'slug',
        'terms' => $term->name,
    )),

'meta_key' => 'publication_date',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'paged' => $paged,
'posts_per_page' => '10',
));

我也嘗試使用 wpdb 並運行 SQL 查詢,但我真的不知道如何完成我想要做的。如果有人可以幫助我,那真是太棒了!

提前致謝。

最佳解決方案

感謝大家的幫助!

最後,下面的查詢給了我所期望的結果 – 這是為了顯示和排序”publication_date” 的自定義字段的職位,按日期排序,如果有多個相同的日期 (例如,標記為 2013 年 6 月的 4 個),它會按標題排序。然後,在通過所有發佈日期填寫完畢的帖子之後,它將再次按照標題按字母順序循環遍歷剩餘的帖子。

這讓我在同一查詢中設置結果,並保持我的分頁:

$term = get_queried_object();
the_post();
$wp_query = new WP_Query( array(
'post_type' => 'resource',
    'tax_query' => array(
        array(
            'taxonomy' => 'resource_types',
            'field' => 'slug',
            'terms' => $term->name,
        )),
 'meta_query' => array(
       'relation' => 'OR',
        array( //check to see if date has been filled out
                'key' => 'publication_date',
                'compare' => '=',
                'value' => date('Y-m-d')
            ),
          array( //if no date has been added show these posts too
                'key' => 'publication_date',
                'value' => date('Y-m-d'),
                'compare' => 'NOT EXISTS'
            )
        ),
'meta_key' => 'publication_date',
'orderby' => 'meta_value title',
'order' => 'ASC',
'paged' => $paged,
'posts_per_page' => '10',
));

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。