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');
2
Answers
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 ofcat
).So just remove that space, i.e.
'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: