首页 > 解决方案 > 仅显示自定义帖子中某个类别的帖子

问题描述

我在 Wordpress 中创建了一个自定义帖子类型,并设置了一些带有“显示”类别的帖子,它的 id 是 3,我怎样才能只显示这个类别的帖子?我尝试了下面的代码,但它显示了所有类别的帖子。

            <?php
            $args = array(
            'post_type' => 'devices',
            'cat '=> '3',
            'posts_per_page' => 3);
            
            $my_query = new WP_Query( $args );
            
            if( $my_query->have_posts() ) {
                while ($my_query->have_posts()) : $my_query->the_post(); ?>

函数.php:

    // Custom Post Type | devices
function custom_post_type_devices() {
    register_post_type('devices', array(
    'map_meta_cap' => true, 
       'description' => 'devices',
       'public' => true,
       'show_ui' => true,
       'show_in_menu' => true,
       'capability_type' => 'post',
       'map_meta_cap' => true,
       'hierarchical' => false,
       'rewrite' => array('slug' => 'devices', 'with_front' => true),
       'query_var' => true,
       'supports' => array('title', 'page-attributes','post-formats', 'thumbnails'),
       'menu_icon' => 'dashicons-groups',         
       'taxonomies' => array('recordings', 'category'),
     
       'labels' => array (
          'name' => 'devices',
          'singular_name' => 'device',
          'menu_name' => 'devices',
          'edit' => 'edit',
          'edit_item' => 'edit device',
          'new_item' => 'New device',
          'view' => 'See device',
          'view_item' => 'See device',
          'search_items' => 'Search device',
          'not_found' => 'Nothing found',
          'not_found_in_trash' => 'Nothing found',
       )
    ));
 }
 add_action('init', 'custom_post_type_devices');

标签: phpwordpresscustom-post-type

解决方案


Your code is already querying only posts from a specific category, but you made a typo here: 'cat '=> '3' — note the space right after the text "cat".

That space invalidates the argument name (which becomes cat instead of cat).

So just remove that space, i.e. 'cat'=> '3', and your code would work as expected.


推荐阅读