简体   繁体   中英

WP custom post type query does not return custom taxonomy

I have the following CPT:

        array(
            'slug'        => 'articles',
            'single_name' => 'Article',
            'plural_name' => 'Articles',
            'menu_name'   => 'Articles',
            'description' => '',
            'dashicon'    => 'dashicons-media-default'
        ),

and the following custom taxonomy which shows up under the articles CPT:

        array(
            'slug'        => 'author',
            'single_name' => 'Author',
            'plural_name' => 'Authors',
            'menu_name'   => '→ Authors',
            // This is where you sync the taxonomy to the post types above
            'post_type'   => ['articles', 'news']
        ),

Now, I am trying to create a single-articles.php in which I query a single article, to include all custom taxonomy information.

I've tried all variations of:

$args = array(
    'post_type' => 'articles',
    'tax_query' => array(
        array(
            'taxonomy' => 'author',
            'field' => 'slug'
        ),
    ),
);

I am relatively new to PHP & WP and am not 100% sure how to retrieve the data. In Javascript you would get an object back through which one can traverse. When adding print_r($my_query) I don't get what back what I am looking for. Earlier in the document I already initiated the loop:

if (have_posts()) :
  while (have_posts()) : the_post()

but I can't figure out why php/wp doesn't show all data included in the object. Ideally, I want to query only the single article and get all data back, to include info about all attached taxonomies . I do not want to query articles BY the taxonomy So I have two questions:

1) How do I query this correctly to get results back? 2) How do I display this data on the frontend?

Edit: According to this tax_query is ignored when is_singular() is true. print_r( is_singular() ) results in 1 (aka true?!), would this make a difference?

I also have custom post types attached to the taxonomies. I need to retrieve this info as well.

Your taxonomy slug is author NOT authors

$args = array(
'post_type' => 'articles',
'posts_per_page' => -1,
'tax_query' => array(
    array(
        'taxonomy' => 'author',
        'field' => 'slug',
        'terms' => 'your-term-here',
    ),
  ),
);

You can Use single-{posttype}.php for the single template.

And, if you have register your post type with the has_archive argument set to true, then you can use archive-{posttype}.php for your archive template.

You can check Template Hierarchy

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM