問題描述

我想使用自定義帖子類型的存檔作為站點的首頁,這樣

 http://the_site.com/

是根據我的 archive-{post-type}.php 文件顯示的自定義帖子類型存檔。

理想情況下,我想在 functions.php 文件中使用 is_front_page()更改查詢。我嘗試了以下,一個名為”Home” 的頁面作為我的首頁:

 add_filter('pre_get_posts', 'my_get_posts');
 function my_get_posts($query){
     global $wp_the_query;
     if(is_front_page()&&$wp_the_query===$query){
        $query->set('post_type','album');
        $query->set('posts_per_page',-1);
     }
     return $query;
 }

但首頁正在返回”Home” 的內容,似乎忽略了自定義查詢。

我究竟做錯了什麼?總的來説,有沒有更好的方法呢?

最佳解決方案

將靜態頁面設置為主頁後,您可以將其添加到您的 functions.php 中,您很好。這也將正確調用 archive-POSTTYPE.php 模板。

add_action("pre_get_posts", "custom_front_page");
function custom_front_page($wp_query){
    //Ensure this filter isn't applied to the admin area
    if(is_admin()) {
        return;
    }

    if($wp_query->get('page_id') == get_option('page_on_front')):

        $wp_query->set('post_type', 'CUSTOM POST TYPE NAME HERE');
        $wp_query->set('page_id', ''); //Empty

        //Set properties that describe the page to reflect that
        //we aren't really displaying a static page
        $wp_query->is_page = 0;
        $wp_query->is_singular = 0;
        $wp_query->is_post_type_archive = 1;
        $wp_query->is_archive = 1;

    endif;

}

次佳解決方案

Re-name 您的 CPT 檔案歸檔到 home.php

然後使用 pre_get_posts 更改主頁查詢,以便只顯示 CPT 的顯示

function wpsites_home_page_cpt_filter($query) {
if ( !is_admin() && $query->is_main_query() && is_home() ) {
$query->set('post_type', array( 'your-cpt' ) );
    }
  }

add_action('pre_get_posts','wpsites_home_page_cpt_filter');

用您的自定義帖子類型的名稱替換 your-cpt 。

參考文獻

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