1

I am trying to output related posts of the current post by tag_ID. With the current code, posts will output all posts from the property tag instead of specific tag.

How can I only return posts based on the current posts 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: Might not be the best solution but manages to query related posts that are within city and the current posts tag.

$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 );
2

get_the_tags() returns an array of tags name, ID, and more. You should store only IDs in an array, and use it in your query.

$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 );

Also, use wp_reset_postdata(); instead of wp_reset_query(); when you are using WP_Query();.

UPDATE

As pointed out by @birgire, WordPress offers the wp_list_plunk() function to extract a certain field of each object in a row, which has the same functionality as array_column() function.

So, we can change this:

// 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; 
    }
}

To this:

// Check if the post has any tags
if ( $post_tag ) {
    $ids = wp_list_pluck( $post_tag, 'term_id' );
}
  • 1
    There are also handy functions like wp_list_pluck() to help pluck out a given field from an object. – birgire Aug 25 '17 at 18:16
  • 1
    yes, an array of WP_Term objects, if I recall correctly, if successful – birgire Aug 25 '17 at 18:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.