我正在尝试输出当前帖子的相关帖子tag_ID
. 使用当前代码,posts将从property
标记而不是特定标记。
我如何才能只返回基于当前帖子的帖子tag_ID
?
<?php $post_tag = get_the_tags($post->ID)?>//Not sure if correct
<?php
$args = array(
\'post_type\' => \'property\',
\'tag\' => $post_tag,
);
$related_posts = new WP_Query( $args );
?>
<?php while ( $related_posts -> have_posts() ) : $related_posts -> the_post(); ?>
<h2><?php echo get_the_title()?></h2>
//etc
<?php endwhile; wp_reset_query(); ?>
Solution:可能不是最好的解决方案,但可以查询
city
和当前的posts标签。
$tags = wp_get_post_terms( get_queried_object_id(), \'city\', [\'fields\' => \'ids\'] );
// Now pass the IDs to tag__in
$args = array(
\'post_type\' => \'property\',
\'post__not_in\' => array( $post->ID ),
\'tax_query\' => array(
array(
\'taxonomy\' => \'city\',
\'terms\' => $tags,
),
),
);
$related_posts = new WP_Query( $args );
最合适的回答,由SO网友:Johansson 整理而成
get_the_tags()
返回标记name、ID等的数组。您应该只在数组中存储ID,并在查询中使用它。
$post_tag = get_the_tags ( $post->ID );
// Define an empty array
$ids = array();
// Check if the post has any tags
if ( $post_tag ) {
foreach ( $post_tag as $tag ) {
$ids[] = $tag->term_id;
}
}
// Now pass the IDs to tag__in
$args = array(
\'post_type\' => \'property\',
\'tag__in\' => $ids,
);
// Now proceed with the rest of your query
$related_posts = new WP_Query( $args );
此外,使用
wp_reset_postdata();
而不是
wp_reset_query();
当您使用
WP_Query();
.
因此,我们可以改变这一点:
// Define an empty array
$ids = array();
// Check if the post has any tags
if ( $post_tag ) {
foreach ( $post_tag as $tag ) {
$ids[] = $tag->term_id;
}
}
对此:
// Check if the post has any tags
if ( $post_tag ) {
$ids = wp_list_pluck( $post_tag, \'term_id\' );
}