WordPress ACF passing a variable as a value into args array

Question

I’m trying to create a dynamic posts layout. In the backend, I have a field where I enter the slug of the post collection I want to pass in.

The $subfield value is recipe. For some reason, when I write ‘post_type’ => $subfield it’s not working. It only works when I hardcode it. Any insight as to why my $subfield variable is empty when I pass it as a value to ‘post_type’

<?php 

if ( 
get_row_layout() == 'list_posts' ) {

// $subfield = the_sub_field( 'custom_post_type' );
// this variable has a string value of recipe in the backend

    
$args = array(
  'post_type'   => 'recipe' //works when hardcoded, not when $subfield is passed
 );


 $the_query = new WP_Query($args );

 if (
 $the_query->have_posts() )
 :while (
 $the_query->have_posts() )
 : $the_query->the_post();
 ?>

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

  

  <?php wp_reset_postdata();
      endwhile;
      endif;
    } 

  ?>
0
Catherine Khvorost 4 months 0 Answers 24 views 0

Leave an answer