嵌套的foreach循环无法正常运行。 -wp

时间:2018-08-16 14:07:34

标签: php wordpress advanced-custom-fields

我有定制的职位类型“库存商”和“产品”,后者具有分类法“范围”。使用ACF过帐对象将产品分配给库存商。

我正在尝试遍历“库存商”,从发布对象返回“范围”术语,然后列出每个术语的产品。到目前为止,我可以循环所有库存商并返回所有范围条款,但是返回产品列表的foreach循环似乎并没有循环,因为它仅返回每个库存商的第一组值。

谁能看到我要去哪里错了?

<?php                           
$args2 = array( 'post_type' => 'stockist', 'posts_per_page' => -1 );
$stockistloop2 = new WP_Query( $args2 );
if ( $stockistloop2->have_posts() ): while ( $stockistloop2->have_posts() ): $stockistloop2->the_post();?>
<div class="col-1-1 clearfix nopad stockist-block-dropdown <?php the_title();?>-block">
    <?php 
$args = array( 'taxonomy' => 'range', 'hide_empty' => 0);
$categories = get_categories($args);
 if($categories): foreach($categories as $category): $url = get_category_link( $category->term_id ); ?>
    <div class="col-1-5">
        <h4>
            <?php echo ($category->name) ;?>
        </h4>
        <ul class="stockist-block-products clearfix">
            <?php $post_objects = get_field('stocked_range'); if( $post_objects ): 
            foreach( $post_objects as $post): $post_terms_array = get_the_terms($post, 'range'); $post_term_name = $post_terms_array[0]->slug; 
            setup_postdata($post); 
            if($post_term_name == $category->slug):?>
            <li>
                <a href="<?php the_permalink(); ?>">
                    <?php the_title(); ?>
                </a>
            </li>
            <?php endif;
            endforeach; 
            endif;?>
        </ul>
    </div>
    <?php endforeach; ?>
    <?php endif;?>
</div>
<?php endwhile; wp_reset_postdata(); endif; ?>

更新

用以下内容替换内部循环已解决了该问题:

<?php $post_objects = get_field('stocked_range');
if( $post_objects ): ?>
    <ul class="stockist-block-products clearfix">
    <?php foreach( $post_objects as $post_object): $post_terms_array = get_the_terms($post_object, 'range'); $post_term_name = $post_terms_array[0]->slug; 
        if($post_term_name == $category->slug):?>
        <li>
            <a href="<?php echo get_permalink($post_object->ID); ?>"><?php echo get_the_title($post_object->ID); ?></a>
            <span>Post Object Custom Field: <?php the_field('field_name', $post_object->ID); ?></span>
        </li>
        <?php endif; endforeach; ?>
    </ul>
<?php endif;?>

0 个答案:

没有答案