2013-09-23 39 views
0

我需要在歸檔循環中顯示自定義帖子類型'vehicle'的所有現有帖子。無限posts_per_page只適用於自定義帖子類型

這是我到目前爲止有:

function get_all_vehicle_posts($query) { 
    $query->set('posts_per_page', '-1'); 
} 
add_action('pre_get_posts', 'get_all_vehicle_posts'); 

而且我看到了無限的帖子,我想。不過,我需要將此更改限制爲我的自定義帖子類型。

我想:

if ('vehicle' == $query->post_type) { 
     $query->set('posts_per_page', '-1'); 
    } 

,但似乎並沒有工作。我猜我們不知道查詢運行前的帖子類型,除非它是查詢的特定參數?

如何限制此功能爲特定的帖子類型?

回答

6

使用is_post_type_archive函數對帖子類型進行檢查。

您將需要檢查查詢是否不是管理員以避免影響管理員區域,以及檢查查詢是否爲主要查詢。

function get_all_vehicle_posts($query) { 
    if(!is_admin() && $query->is_main_query() && is_post_type_archive('vehicle')) { 
     $query->set('posts_per_page', '-1'); 
    } 
} 
add_action('pre_get_posts', 'get_all_vehicle_posts'); 

http://codex.wordpress.org/Function_Reference/is_admin

http://codex.wordpress.org/Function_Reference/is_main_query

http://codex.wordpress.org/Function_Reference/is_post_type_archive

+0

這正是我需要+1來支持它的引用 - 謝謝;) – gpcola

+0

這不是爲我工作,我無法弄清楚爲什麼!我正在一個自定義的歸檔頁面,所以我實際上需要:'$ query-> set('posts_per_archive_page','-1');' –

0

的職位類型必須設置爲查詢參數

$args = array(
    'post_type' => 'vehicle' 
); 

所以在你的函數加職位類型,否則你只能查詢標準的主對象。

+0

以我環路I'具有query_posts( 'post_type =車輛'); while(have_posts()):the_post();' - 不應該是一樣嗎?如果不是我應該設置post_type參數的地方? – gpcola

+0

@gpcola你可以將數組放到你設置每頁帖子的位置,它應該讀取查詢參數 – Anagio

+0

我試過了:'$ args = array('post_type'=>'vehicle','posts_per_page'=>' -1'); $ query-> set($ args);'但那不起作用 - 我可能不理解你的意思。 – gpcola

相關問題