如何从分类法术语名称获取post id ?
分类是:post_tagPost_type为:videos我有一个术语名称来获取文章
我试着
$args = query_posts(array(
'post_type' => 'videos',
array(
'taxonomy' => 'post_tag',
'terms' => $term_name,
'field' => 'name'
)
)
);
以下是您当前代码中的几个问题:
- 关于
query_posts
的使用,"此功能不意味着由插件或主题使用"(来源)。使用WP_Query或get_posts代替。 - 你将你的
query_posts
数据分配给一个名为$args
的变量,但它实际上会返回帖子-而不是参数-所以这是混乱的(坏做法)。
$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>';
}
}