wordpress - 无法获取 WP_Query 自定义帖子类型的类别帖子
问题描述
我对自定义帖子类型的 WP_Query 有一些问题,我无法按类别获取自定义帖子。我有:
function my_blocks_render_function( $attributes ) {
$args = array(
'post_type' => 'my_cpt',
'posts_per_page' => $attributes['numberOfPosts']
);
if($attributes['postCategories']) {
$args['cat'] = $attributes['postCategories'];
}
$query = new WP_Query($args);
$posts = '';
if($query->have_posts()) {
$posts .= '<ul>';
while ($query->have_posts()) {
$query->the_post();
$posts .= '<li><a href="' . esc_url( get_the_permalink() ) . '">' . get_the_title() . '</a></li>';
}
$posts .= '</ul>';
wp_reset_postdata();
return $posts;
} else {
return '<div>' . __("No Posts Found", "my-blocks") . '</div>';
}}
使用'post_type'=>'post',一切正常,但自定义帖子类型没有。如果未选择 postTypes,我将获得所有自定义帖子,但如果是“未找到帖子”。
我究竟做错了什么?我尝试添加 tax_query,但结果相同。我 var_dump 我的 postCategories 并获得正确的 ID。
对不起我的英语,谢谢。
解决方案
这将正常工作。
$taxonomy='our_project_category';
$tax_terms = get_terms($taxonomy, array('hide_empty' => false));
foreach($tax_terms as $term_single) {
$categories_id= 2; //category_id
$args_new = array(
'post_type' => 'our-project',
'posts_per_page' => 6,
'tax_query' => array(
array(
'taxonomy' => 'our_project_category',
'field' => 'term_id',
'terms' => $categories_id,
),
),
);
$loop_new = new WP_Query($args_new);
if($loop_new->have_posts()) {
while($loop_new->have_posts()) : $loop_new->the_post();
//content
endwhile; wp_reset_query();
endif;
?>
推荐阅读
- sql-server - SQL Server query for calculating daily census
- javascript - React hooks 函数依赖
- sql - 如何向我的 Hive 表添加分区?
- react-native - 对 firebase 数据库字段的多个查询
- c# - C# Asp Core 2.2 模型绑定对象在 OnGet() 中实例化,但不在 OnPost() 中
- facebook - 如何在 React Native 中启动 ViewContent facebook 事件?
- azure-devops - 来自私有源的 Azure 站点扩展
- dask - 异步 Xarray 写入 Zarr
- c# - 是否有开箱即用的方式将 HTTP 请求的整个主体绑定到 ASP.NET Core 控制器操作中的字符串参数?
- python - 写入 XML 文件需要大数组作为内存中的字符串