简体   繁体   中英

How can I get ACF field value in WordPress loop?

I'm trying to get ACF filed value for post in loop. But for some reason the value is not being displayed.

I've already tried

<?php $field = get_field('field_name'); echo $field;  ?>

And

<?php the_field('field_name', $post->ID); ?>

None of the methods are working. See the loop code below:

<?php 
    $args = array( 
    'post_type' => 'post',
    'posts_per_page' => 4,
    $the_query = new WP_Query( $args );
?>
<?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
    <div class="col-sm-6">

        <h2 class="the-title"><?php the_field('field_name', $post->ID); ?> +  <?php the_title() ;?> </h2>


    </div>

<?php endwhile; else: ?> Nothing here <?php endif; ?>
<?php wp_reset_query(); ?>

How can I get the ACF field values in loop?

Try use

the_field('field_name', get_the_ID());

You haven't closed the array correctly.Please try this

<?php 
        $args = array( 
        'post_type' => 'post',
        'posts_per_page' => 4
       );
        $the_query = new WP_Query( $args );
    ?>
    <?php if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <div class="col-sm-6">

            <h2 class="the-title"><?php the_field('field_name', $post->ID); ?> +  <?php the_title() ;?> </h2>


        </div>

    <?php endwhile; else: ?> Nothing here <?php endif; ?>
    <?php wp_reset_query(); ?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM