問題描述
我已經安裝了 Custom Post Type UI plugin 。啟用此外掛後,我建立了一個名為 portfolio 的自定義帖子型別。現在我想在 front-end 的投資組合頁面上使用。如何獲取自定義帖子型別 portfolio 的所有帖子?
最佳解決方案
query_posts( array( 'post_type' => array('post', 'portfolio') ) );
其中顯示 portfolio 型別中的正常職位和職位
要麼
query_posts('post_type=portfolio');
僅適用於 portfolio 。
使用正常 WP 查詢 – 閱讀食典:http://codex.wordpress.org/Function_Reference/query_posts#Usage 和 http://codex.wordpress.org/Function_Reference/query_posts#Post_.26_Page_Parameters
<?php
query_posts(array(
'post_type' => 'portfolio',
'showposts' => 10
) );
?>
<?php while (have_posts()) : the_post(); ?>
<h2><a href="<?php%20the_permalink()%20?>"><?php the_title(); ?></a></h2>
<p><?php echo get_the_excerpt(); ?></p>
<?php endwhile;?>
次佳解決方案
晚回答主要的答案是使用 query_posts(),這是不應該做的。
使用過濾器
使用 pre_get_posts 過濾器,並設定主查詢的 portfolio 後置型別。使用 Conditional Tags 確定您想要擁有此過濾器的位置。
快速示例
<?php
defined( 'ABSPATH' ) OR exit;
/* Plugin Name: (#6417) "Portfolio" post type in query */
add_filter( 'pre_get_posts', 'wpse_6417_portfolio_posts' );
function wpse_6417_portfolio_posts( $query )
{
if (
! $query->is_main_query()
// Here we can check for all Conditional Tags
OR ! $query->is_archive() // For e.g.: Every archive will feature both post types
)
return $query;
$query->set( 'post_type', array( 'post', 'portfolio' ) );
return $query;
}
Disclaimer
上面的程式碼是一個外掛,但可以簡單地填入你的主題的 functions.php 檔案 (不推薦) 。
第三種解決方案
將此程式碼新增到您的子主題功能檔案 (推薦) 以將單個 CPT 頁面新增到主迴圈中
add_action( 'pre_get_posts', 'add_custom_post_types_to_loop' );
function add_custom_post_types_to_loop( $query ) {
if ( is_home() && $query->is_main_query() )
$query->set( 'post_type', array( 'post', 'portfolio' ) );
return $query;
}
來源 http://codex.wordpress.org/Post_Types
或者只顯示您的 CPT 頁面的 create a custom archive-portfolio.php page template 。如果您尚未使用外掛設定新增存檔頁面,則僅需完成此操作。
示例:’has_archive’ => 真正,
您還可以使用以下程式碼控制在存檔頁面上顯示的頁面數量和顯示順序:
add_action( 'pre_get_posts', 'cpt_items' );
function cpt_items( $query ) {
if( $query->is_main_query() && !is_admin() && is_post_type_archive( 'portfolio' ) ) {
$query->set( 'posts_per_page', '8' );
$query->set( 'order', 'ASC' );
}
}
參考文獻
注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。