我已安装Custom Post Type UI plugin. 激活此插件后,我创建了一个名为portfolio
. 现在我想在前端的公文包页面上使用它。如何获取所有自定义帖子类型的帖子portfolio
?
Query for custom post type?
3 个回复
最合适的回答,由SO网友:Martin-Al 整理而成
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 the_permalink() ?>"><?php the_title(); ?></a></h2>
<p><?php echo get_the_excerpt(); ?></p>
<?php endwhile;?>
SO网友:kaiser
延迟回答作为主要回答使用query_posts()
, 哪个应该never 完成
使用过滤器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;
}
上述代码是一个插件,但可以简单地塞进functions.php
主题文件(即not 建议)。SO网友:Brad Dalton
将此代码添加到child themes functions file (推荐)将单个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或create a custom archive-portfolio.php page template 只显示您的CPT页面。只有在没有使用插件设置添加存档页面时,才需要执行此操作。
示例:“has\\u archive”=>true,
您还可以使用以下代码控制显示的页面数量以及它们在存档页面上的显示顺序:
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\' );
}
}
结束