Support

Account

Home Forums Gutenberg How to show a post's custom fields inside wp_query inside block render?

Solving

How to show a post's custom fields inside wp_query inside block render?

  • I have a block that shows a wp_query loop. It works, except it doesn’t show the posts’ custom fields. When I use this code in a regular template file it works, but doesn’t when I used it as a block.

    How do I use custom fields inside wp_query in a block render?

    My code (there are two. custom fields: message and issue):

    
    ?>
    <?php
    $args = array(
    'showposts'   => 3,
    'post_status' => array( 'publish', 'future' ),
    );
    
    $the_query = new WP_Query( $args );
    
    if ( $the_query->have_posts() ) { ?>
    
      <div class="post-grid__wrap">
    
        <div class="post-grid">
    
          <?php while ( $the_query->have_posts() ) {
            $the_query->the_post(); ?>
    
            <?php
            $message = get_field('scheduled_message');
            $issue = get_field('issue');
            ?>
            
            <a href="<?php the_permalink(); ?>" rel="bookmark">
              <div class="post-grid__post">
                <div class="post-grid__img">
                  <?php the_post_thumbnail('full'); ?>
                </div>
                <div class="post-grid__text">
                  <p><?php echo $issue; ?></p>           
                    <?php the_title( '<h3>', '</h3>' ); ?>               
                </div>
    
                <?php if( $message && get_post_status() == 'future' ) { ?>
                  <div class="sticker post-grid__sticker">
                    <div class="sticker__text">
                      <p><?php echo $message; ?></p>
                    </div>
                    <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 140 140">
                      <circle cx="70" cy="70" r="70" />
                    </svg>
                  </div>
                <?php } ?>               
              
              </div> 
            </a>           
    
          <?php } // end while ?>
    
        </div>
    
      </div>
    
    <?php } ?>
    
    <?php wp_reset_postdata(); ?>
    
  • I’m just guessing here but, in a template file the global $post is always available. This may not be the case in the code you are running. I would try adding

    
    global $post;
    

    before your query.

  • I got this to work by adding
    global $post;
    and then adding that to the retrieval of ACF fields:

    
    $job_description    =   get_field('job_description', $post->ID );
    $job_type           =   get_field('job_type', $post->ID);
    $job_location       =   get_field('job_location', $post->ID);
    
Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.