在转发器字段中发布对象(WordPress ACF)

时间:2013-11-22 15:31:51

标签: php wordpress advanced-custom-fields

我在 WordPress 中使用 ACF

我有一个名为Projects的自定义帖子类型。在那里,用户可以选择通过ACF转发器字段上传 2 特色图像。

现在,在主页上,我已经为用户提供了从项目帖子类型中选择 8 Post Object 的选项。

我需要能够遍历此主页转发器字段,每个'项目'帖子中拉出特色图片项目标题对象

ACF最近贬低了repeater_field功能,我认为它让我不在这里。

但是,到目前为止,我一直在努力解决这个问题:

<!-- check for repeater field -->
<?php if(get_field('featured-projects')): ?>

    <?php while(has_sub_field('featured-projects')): ?>

        <!-- get project post objects -->
        <?php $projects = get_sub_field('project'); ?>

        <!-- without the loop below, this echo's all 8 projects ID's -->
        <?php echo($projects->ID); ?><br />

        <!-- when added, only pulls the first project. And limits the echo above to the first ID -->
        <?php $loop = new WP_Query( array( 
            'post_type' => 'projects',
            'p' => $projects->ID
        ) ); ?>

        <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>

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


        <?php endwhile; ?>


    <?php endwhile; ?>

<?php endif; ?>

我试图评论代码,但如果有什么不合理的话,请告诉我。

1 个答案:

答案 0 :(得分:0)

这是我如何做到的,虽然我意识到它与你的方法不同。我在代码注释中包含了解释:

<?php $featured_projects = get_field('featured-projects'); //Set $featured_projects to equal the array of projects from the home page repeater. ?>

<!-- check for repeater field -->
<?php if($featured_projects): ?>

      <?php foreach($featured_projects as $featured_project) : //Loop through each featured project ?>

          <?php  $project_id = $featured_project['project']->ID; //Get the id for the current featured project ?>

          <?php $project_title = get_the_title($project_id); //set $title to be the title of the project ?> 
          <?php project_featured_images = get_field('name-of-featured-repeater-field-here', $project_id); //get the repeater field of the featured images from the project post ?>



          <h1 class='title'><?php echo $project_title; //print the title ?></h1>

          <?php if($project_featured_images[0]): //check if you have a 1st image (size large) ?> 
              <img class='featured-image-one' src="<?php echo $project_featured_images[0]['name-of-the-featured-image-sub-field-here']['sizes']['large']; //print the url to the 1st image; ?>"/>
          <?php endif; ?>

          <?php if($project_featured_images[1]): //check if you have a 2nd image ?> 
              <img class='featured-image-two' src="<?php echo $project_featured_images[1]['name-of-the-featured-image-sub-field-here']['sizes']['large']; //print the url to the 2nd image (size large); ?>"/>
          <?php endif; ?>

      <?php endforeach; ?>

<?php endif; ?>

确保填写项目特色图像转发器字段的名称,以及该转发器中图像子字段的名称。这显然是比API版本更标准的基于PHP的解决方案。我通常根据Elliot Candon(ACF Developer)推荐使用此方法。

您还可以通过将“大”更改为其他标准尺寸,或添加custom size来获得精选图像的不同图像尺寸。

相关问题