1

i'm trying to display the post from the current category and same tag on a single page.

I'm displaying the post from the current category like below:

<div class="row">
    <?php
    global $post;
    $category = get_the_category($post->ID);
    $category = $category[0]->cat_ID;
    $myposts = get_posts(
                array(
                    'numberposts' => -1, 
                    'offset' => 0, 
                    'category__in' => array($category),
                    'post_status'=>'publish',
                    'order'=>'ASC' 
                    )
                );
    foreach($myposts as $post) :
        setup_postdata($post);  ?>
        <div class="col-md-3 animation-element bounce-up cf" <?php post_class(); ?> id="post-<?php the_ID(); ?>">
            <a class="test" href="<?php the_permalink(); ?>">
            <?php echo get_the_post_thumbnail( $post->ID, 'large' ); ?> </a>
                <p style="text-transform:uppercase;text-align:center;font-size:18px;margin-top:20px" class="title"><strong>
            <?php the_title(); ?> </strong> </p>
        </div>
    <?php endforeach; ?>
    <?php wp_reset_query(); ?>
</div>

but how to display also from the same tag as the current post ?

Thanks a lto !

1
  • You can simply use tag__in, just like category__in.
    – Johansson
    Commented Jul 16, 2017 at 16:58

1 Answer 1

1

Tags are a taxonomy called post_tag. You can use them in get_posts() via the tax_query.

Since wp_get_post_tags() returns an array of objects, you need to clean it up a bit since only one field per object is required for the query.

$tag_objects = wp_get_post_tags($post->ID);
$tags = array();
foreach ($tag_objects as $tag_object) {
    $tags[] = $tag_object->term_id;
}
$myposts = get_posts(array(
    'numberposts' => -1,
    'offset' => 0,
    'category__in' => array($category),
    'tax_query' => array(
        array(
            'taxonomy' => 'post_tag',
            'field'    => 'term_id',
            'terms'    => $tags,
        ),
    ),
    'post_status'=>'publish',
    'order'=>'ASC'
));
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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