问题描述

我已经安装了 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#Usagehttp://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 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。