ACF Querying custom post types with taxonomies

2019-08-10 06:45发布

问题:

I can query and display all custom post types, but when trying to query them based on taxonomy as well it will not work. Somebody please help!

Taxonomy function

add_action( 'init', 'create_project_type_taxonomies', 0 );

function create_project_type_taxonomies() {
// Add new taxonomy, make it hierarchical (like categories)
$labels = array(
    'name'              => _x( 'Project Types', 'taxonomy general name' ),
    'singular_name'     => _x( 'Project Type', 'taxonomy singular name' ),
    'search_items'      => __( 'Search Project Types' ),
    'all_items'         => __( 'All Project Types' ),
    'parent_item'       => __( 'Parent Project Type' ),
    'parent_item_colon' => __( 'Parent Project Type:' ),
    'edit_item'         => __( 'Edit Project Type' ),
    'update_item'       => __( 'Update Project Type' ),
    'add_new_item'      => __( 'Add New Project Type' ),
    'new_item_name'     => __( 'New Project Type' ),
    'menu_name'         => __( 'Project Type' ),
);

$args = array(
    'hierarchical'      => true,
    'labels'            => $labels,
    'show_ui'           => true,
    'show_admin_column' => true,
    'query_var'         => true,
    'rewrite'           => array( 'slug' => 'project_type' ),
);

register_taxonomy( 'project_type', array( 'project' ), $args );
}

Query - which works without the taxonomy line

<?php 
        $projects = new WP_Query(
            array(
                'post_type' => 'project',
                'project_type' => 'music_videos',
            )
        ); 
        ?>

        <?php if($projects->have_posts()) : ?>
        <?php while($projects->have_posts()) : $projects->the_post(); ?>

                <!--some query stuff which works-->

                <?php endwhile; ?>
    <?php endif; wp_reset_query(); ?>

回答1:

You have to use tax_query parameter, like described here

$args = array(
    'post_type' => 'project',
    'tax_query' => array(
        array(
            'taxonomy' => 'project_type',
            'field'    => 'slug',
            'terms'    => 'music_videos',
        ),
    ),
);
$projects = new WP_Query( $args );

Hope it helps :)