WordPress,foreach分类学显示重复项

时间:2018-11-22 10:22:44

标签: php wordpress foreach

我有以下代码,它首先针对以下事实工作:它显示了所有分类法的产品。但是,如果产品设置为2个分类法,则它将在页面上显示两次,而不是显示产品的第一个实例。

<?php if ( $terms && !is_wp_error( $terms ) ) {
    foreach ( $terms as $term ) {

        $args = array(
            'post_type'  => 'products',
            'posts_per_page' => -1,
            'orderby' => 'menu_order',
            'tax_query' => array(
                array(
                    'taxonomy' => 'product_cat',
                    'field'    => 'slug',
                    'terms'    => $term->slug,
                ),
            ),
            'order' => 'asc',
        );

        runQuery($args);
    }
} ?>

这是runQuery函数:

<?php $x = 0;
function runQuery($args) {
    global $x;
    $query = new WP_Query( $args );

    if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post();
        $cat_terms = get_the_terms($post->id, 'product_cat');
        $datagroups = '';

        foreach ($cat_terms as $key => $cat) {
            if (count($cat_terms) == ($key + 1)) {
                $datagroups .= '"' . $cat->name . '"';
            } else {
                $datagroups .= '"' . $cat->name . '", ';
            }
        }
    ?>      

    HTML Here that is displayed;

    <?php $x ++;
    endwhile;
    endif;
    wp_reset_postdata();
}?>

1 个答案:

答案 0 :(得分:0)

我已经弄清楚了,基本上我只需要检查循环中的当前帖子,看看它是否已经显示:

<?php $x = 0;
$displayed = [];

function runQuery($args) {
    global $displayed;
    global $x;
    $query = new WP_Query( $args );

    if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post();
        $cat_terms = get_the_terms($post->id, 'product_cat');
        $datagroups = '';

        if ( in_array( get_the_ID(), $displayed ) ){
            continue;
        }
        // update array with currently displayed post ID
        $displayed[] = get_the_ID();

        foreach ($cat_terms as $key => $cat) {
            if (count($cat_terms) == ($key + 1)) {
                $datagroups .= '"' . $cat->name . '"';
            } else {
                $datagroups .= '"' . $cat->name . '", ';
            }
        }
    ?>  

可能对他人有帮助的来源:https://wordpress.stackexchange.com/questions/285091/avoid-duplicate-post-from-same-taxonomy