Wordpress 自定义 Post 用作主页的类型类别

Wordpress Custom Post Type category used as homepage

我有一个名为 portfolio 的自定义 Post 类型和一个名为 narrative.

的自定义分类法 portfolio_category

我可以使用 URL /portfolio-category/narrative/.

访问存档页面

我希望主页在不使用重定向的情况下显示与叙述存档页面上相同的所有项目。

我已将以下内容添加到 functions.php

function custom_front_page($wp_query){
    if($wp_query->get('page_id')==get_option('page_on_front')){
        $wp_query->set('post_type','portfolio');
        $wp_query->set('page_id',''); // empty
        // fix conditional functions
        $wp_query->is_page = false;
        $wp_query->is_archive = true;
        $wp_query->is_post_type_archive = true;
    }
}
add_action('pre_get_posts','custom_front_page');

这显示了我主页上的所有投资组合项目,但我希望它只显示 narrative 个项目。

我已经在 php 模板文件中尝试过,但它也不起作用

<?php
    $custom_query_args = array(
    'post_type'  => 'portfolio',
    'portfolio_category' => 'narrative',
    );

    $custom_query = new WP_Query( $custom_query_args ); 
?>

如何才能只显示在主页上的叙述项目?

您走对了,但您没有正确地按自定义分类法进行搜索。按自定义分类法搜索不同于按类别搜索。

如果您查看 WP_Query documentation for searching by taxomony,您会发现您需要使用 tax_query 来搜索自定义分类术语的帖子。

您可以在主页模板文件中使用以下代码。评论解释了每个部分的作用:

$args = array(
    'post_type' => 'portfolio',
    'posts_per_page' => 5, // number of results to get, or -1  to get all of them
    'tax_query' => array(  
        array(           // important note, this is an array inside the tax_query arrays
            'taxonomy' => 'portfolio_category', // your custom taxonomy
            'field' => 'slug', // what to search, e.g. slug, term_id, name
            'terms' => 'portfolio' // the term(s) to search for. If you want to search for multiple terms, you can use an array
        )
    )
)

// do a new query with your arguments
$portfolio_query = new WP_Query($args);

// if the query returns any results, loop through them and process them as required
if( $portfolio_query->have_posts() ):
    while ( $portfolio_query->have_posts() ) :
        $portfolio_query->the_post();
        // do stuff with the post here, e.g. display the post...
    endwhile;
endif;

// IMPORTANT! The custom query will overwrite the $post values that are used in the the_post etc.
// This restores the the current post in the main query - i.e. your homepage post.
wp_reset_postdata();