【问题标题】:Wordpress WP_Query - Related posts based on taxonomyWordpress WP_Query - 基于分类的相关帖子
【发布时间】:2014-01-13 09:51:46
【问题描述】:

我正在尝试构建一个 WP_Query,它循环浏览来自某个自定义帖子类型(在本例中为当前产品)的帖子,并返回所有标记有相同分类的帖子(在本例中,相同分类作为正在显示的帖子)

这是我目前所拥有的:

<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>

【问题讨论】:

    标签: php wordpress post taxonomy


    【解决方案1】:

    试试这个:

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

    您应该将代码中出现的your-taxonomy 替换为您的分类类型,以便此代码正常工作。

    【讨论】:

    • 这似乎不起作用?被查询的分类需要与被显示的帖子相同...
    • 什么意思?请解释一下。
    • 显示的单个帖子将具有一定的分类,我需要相关帖子仅在它们具有相同的分类时显示。我希望这会有所帮助...
    • 您使用的是哪种分类法?你能更具体一点吗?我们可以查询帖子是术语,而不是分类。
    猜你喜欢
    • 1970-01-01
    • 2023-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多