首页 > 解决方案 > 如何在具有帖子类型的自定义页面上显示所有图像字段

问题描述

我正在尝试遍历 ACF 的字段以显示帖子类型和特定类别的所有图像

我举一个实际的例子:我有一个 ACF 图像字段(image_of_project),我想查看与 XYZ 类别关联的帖子类型(项目)中上传的所有图像

现在我创建了这个循环:

'

        $loop = new WP_Query( array( 
            'post_type' => 'projects',
            'posts_per_page' => 9,
            ) );
        
        while ( $loop->have_posts() ) : $loop->the_post();
        $images = get_field('image_of_project');
        if( $images ): ?>
                <?php foreach( $images as $image ): ?>
                
                        <div class="item">
                            <a href="<?php echo get_permalink( $post->ID ); ?>" target="_blank">
                            <?php echo wp_get_attachment_image( $image ); ?>
                            </a>
                        </div>
                <?php endforeach; ?>     
        <?php endif; ?>
        <?php endwhile; ?>

'

图像已显示,但我不明白为什么它会重复我每张图像,而不是只显示链接到特定类别的图像。

感谢任何将帮助我完成这项任务的人!

标签: imageadvanced-custom-fieldscustom-post-typecustom-taxonomy

解决方案


对于那些对该功能感兴趣的人,这就是它对我的工作方式。

函数.php

// Loop Gallery Cat1

function my_custom_gallery_cat1() {
    query_posts(array(
        'post_type' => 'gd_project',
        'orderby' => 'rand',
        'posts_per_page' => 10,
        'tax_query' => array(
            array (
                'taxonomy' => 'gd_projectcategory',
                'field' => 'slug',
                'terms' => 'example-terms',
            )
        ),
    ));
    ?> <div class="masonry">
    <?php
    while (have_posts()) : the_post();
        $image_field = get_field('image');
        $image_url = $image_field['url'];
        $image_alt = $image_field['alt']; ?>
        <div class="grid-item">
        <a href="<?php echo get_permalink( $post->ID ); ?>" target="_blank">
        <img src="<?php echo esc_url($image_url); ?>" alt="<?php echo esc_attr($image_alt); ?>" />
        <h4><?php the_field( 'title' ); ?></h4>
        </a>
        </div>
    <?php endwhile; ?>
    </div> <?php
}
add_shortcode('example-terms', 'my_custom_gallery_cat1');

单例.php

<div class="container-fluid">
 <div class="row">
  <?php echo do_shortcode('[categoria]');?>
 </div>    
</div>

推荐阅读