سؤال

I'm trying to build a WP_Query, that cycles through posts from a certain custom post type (in this case current-products), and returns all the posts that are tagged with the same taxonomy (in this case, the same taxonomy as the post being displayed)

This is what I have so far:

<ul>
<?php query_posts('post_type=current-products');
if (have_posts()) : while (have_posts()) : the_post(); ?>

    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>

<?php endwhile; endif; ?>
<?php wp_reset_query(); ?>
</ul>
هل كانت مفيدة؟

المحلول

Try this:

$post_terms = wp_get_object_terms($post->ID, 'your-taxonomy', array('fields'=>'ids'));

$args = array(
    'post_type' => 'current-products',
    'tax_query' => array(
        array(
            'taxonomy' => 'your-taxonomy',
            'field' => 'id',
            'terms' => $post_terms
        )
    )
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
        echo '<ul>';
    while ( $the_query->have_posts() ) {
        $the_query->the_post();
        ?>
                    <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
            <?php
    }
        echo '</ul>';
} else {
    // no posts found
}
wp_reset_postdata();

You should replace occurrences of your-taxonomy in the code with your taxonomy type in order this code to work.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top