如何从分类学术语名称获取帖子ID?
分类标准是:post_tag post_type是:视频 我有用来获取帖子的术语名称
我试过
$args = query_posts(array(
'post_type' => 'videos',
array(
'taxonomy' => 'post_tag',
'terms' => $term_name,
'field' => 'name'
)
)
);
答案 0 :(得分:0)
以下是您当前代码的一些问题:
query_posts
的使用," 此功能并非意图由插件或主题使用" (source)。请改用WP_Query或get_posts。query_posts
数据分配给名为$args
的变量,但它实际上会返回帖子而不是参数 - 这样会让人感到困惑(不良做法)。以下是使用get_posts的解决方案:
$args = array(
'post_type' => 'videos',
'tax_query' => array(
array( // note: tax_query contains an array of arrays. this is not a typo.
'taxonomy' => 'post_tag',
'field' => 'slug',
'terms' => $term_name,
),
),
);
// Collect an array of posts which are given the "post_tag" which includes $term_name
$posts = get_posts( $args );
if ( $posts ) {
// Display the first post ID:
echo $posts[0]->ID;
// Display all posts with "ID: Title" format
foreach( $posts as $the_post ) {
echo $the_post->ID . ': ' . $the_post->post_title . '<br>';
}
}