简体   繁体   中英

Show posts only from a category in custom posts

I created a custom post type in Wordpress and set some posts with the category "show" and its id it's 3, how can I show only posts from this category? I tried the code below but it's showing posts from all the cateogories.

            <?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(); ?>

Functions.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');

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, ie 'cat'=> '3' , and your code would work as expected.

This was already answered here: https://wordpress.stackexchange.com/questions/161330/filtering-wp-query-result-by-category

In resume, you can do the next:

$args = [
    'post_type' => 'devices',
    'posts_per_page' => 3,
    'tax_query' => [
        'relation' => 'AND',
        [
            'taxonomy' => 'category',
            'field'    => 'term_id',
            'terms'    => 3,
        ],
    ],
];
$query = new WP_Query( $args );

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