Foub
Foub

Reputation: 295

How can I retrieve an ACF field from a custom post type to the archive page of this CPT?

I create a Custom Post Type with ACF field inside. Everything works great, but when I want to create my archive-cpt.php page, I can't get my ACF field to be seen on this page.

Here is my archive page code :

<?php get_header(); ?>

<main role="main">
    <!-- section -->
    <section>

  <h1><?php _e( 'Archives', 'trad' ); ?></h1>

  <div class="container">
  <div class="row"> 

  <?php if (have_posts()): while (have_posts()) : the_post(); ?>
  <div class="col-lg-4 mx-auto">

  <!-- article -->

  <h2 class="titre-extranet-article">


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

<li>

    <?php  // display a sub field value
    get_sub_field('titre'); ?></li>
    </div>

    <!-- /post thumbnail -->

    <?php endwhile; ?>

    <?php else: ?>

    <!-- article -->
    <article>
    <h2><?php _e( 'Sorry, nothing to display.', 'trad' ); ?></h2>
    </article>
    <!-- /article -->
    <?php endif; ?>

    </div>
    </div>
        <?php get_template_part('pagination'); ?>

    </section>
    <!-- /section -->
    </main>


    <?php get_footer(); ?>

The sub field 'titre' doesn't appear on my archive page. Where I am wrong ?

Thank you.

Upvotes: 0

Views: 2415

Answers (2)

Krupal Panchal
Krupal Panchal

Reputation: 1545

You can get that field just with get_field() if it is a single text field.

Try with get_field()

<?php echo get_field('titre'); ?>

And one more thing you forgot to add echo before the get_sub_field(). So try with the echo.

<?php echo get_sub_field( 'titre' ); ?>

Upvotes: 0

Red or Dev
Red or Dev

Reputation: 1

get_sub_field() is for a repeater field. So you need to get the parent first e.g.

if( have_rows('parent_field') ):
    while ( have_rows('parent_field') ) : the_row();
        $titre = get_sub_field('titre');
        // Do something...
    endwhile;
endif;

Upvotes: 0

Related Questions