每页ACF关系字段帖子

时间:2015-12-03 10:12:51

标签: relationship advanced-custom-fields

我使用高级自定义字段来调用我的相关帖子,这一切都运行良好,但我如何调整此代码只能随机调用3个帖子?

提前感谢您的帮助!

<?php 

    $posts = get_field('associate_adverts');

    if( $posts ): ?>
        <?php foreach( $posts as $post): // variable must be called $post (IMPORTANT) ?>
        <?php setup_postdata($post); ?>
            <img src="<?php the_field('advert'); ?>">
        <?php endforeach; ?>
        <?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?>
    <?php endif; ?>

1 个答案:

答案 0 :(得分:0)

我最终以相反的方式将其联系起来,这个解决方案有效。

<?php 

    $adverts = get_posts(array(

        'post_type' => 'adverts',
        'posts_per_page' => '3',
        'meta_query' => array(
            array(

                'key' => 'associate_adverts', // name of custom field
                'value' => '"' . get_the_ID() . '"', // matches exaclty "123", not just 123. This prevents a match for "1234"
                'compare' => 'LIKE'
                    )
                )
            ));

    ?>


    <?php if( $adverts ): ?>

        <?php foreach( $adverts as $advert ): ?>

            <?php $photo = get_field('advert', $advert->ID); ?>

                <img src="<?php echo $photo['url']; ?>"/>


        <?php endforeach; ?>

    <?php endif; ?>