如何查询自定义帖子类型和一个类别的帖子列表?

时间:2017-02-22 21:39:08

标签: php wordpress

此查询应包含自定义帖子类型的所有帖子,其中包含名为“featured”的类别或ID为20.我正在尝试将其设置为静态首页,而不是类别或归档模板

我可以获得自定义帖子类型,但不能获得类别。

global $post;
$args = array( 
    'posts_per_page' => 12,
    'offset'=> 1,
    'post_type' => 'project', // name of custom post type.
    //'category' => 20, // if adding ID of category, no posts are returned.
); 

$lastposts = get_posts( $args );
foreach ( $lastposts as $post ) :
    setup_postdata( $post ); 
    echo the_title();
endforeach; 
wp_reset_postdata(); 

更新:根据要求,这里是自定义帖子类型“project”的register_post_type()。

$args = array(
    'labels'             => $labels,
    'public'             => true,
    'publicly_queryable' => true,
    'show_ui'            => true,
    'can_export'         => true,
    'show_in_nav_menus'  => true,
    'query_var'          => true,
    'has_archive'        => true,
    'rewrite'            => apply_filters( 'et_project_posttype_rewrite_args', array(
        'feeds'      => true,
        'slug'       => 'project',
        'with_front' => false,
    ) ),
    'capability_type'    => 'post',
    'hierarchical'       => false,
    'menu_position'      => null,
    'supports'           => array( 'title', 'author', 'editor', 'thumbnail', 'excerpt', 'comments', 'revisions', 'custom-fields' ),
);

register_post_type( 'project', apply_filters( 'et_project_posttype_args', $args ) );

1 个答案:

答案 0 :(得分:0)

    $args = array(
    'post_type' => 'project',
    'posts_per_page' => 12,
    'tax_query' => array(
        'relation' => 'AND',
        array(
            'taxonomy' => 'category',
            'field'    => 'term_id',
            'terms'    => array( 20 )
        ),
    ),
);
$query_post = new WP_Query($args);
if ( $query_post->have_posts() ) {
....
}
wp_reset_query();