[英]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?我在 Wordpress 中创建了一个自定义帖子类型,并将一些帖子设置为“显示”类别,其 id 为 3,我怎样才能只显示该类别的帖子? 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:功能。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".您的代码已经只查询特定类别的帖子,但您在这里打错了:
'cat '=> '3'
— 请注意文本“cat”后面的空格。
That space invalidates the argument name (which becomes cat
instead of cat
).该空间使参数名称无效(变为
cat
而不是cat
)。
So just remove that space, ie 'cat'=> '3'
, and your code would work as expected.因此,只需删除该空间,即
'cat'=> '3'
,您的代码就会按预期工作。
This was already answered here: https://wordpress.stackexchange.com/questions/161330/filtering-wp-query-result-by-category这已经在这里得到了回答: 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 );
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.