Search code examples
phpwordpresscustom-post-typeadvanced-custom-fields

Pass custom field into wordpress loop array


I've got an advanced custom, outputting a chosen taxonomy, which I'm trying to pass into an array inside a WordPress loop.

The loop, which shows a specific taxonomy of my custom post type, is here:

<?php

$loop = new WP_Query( array(
    'post_type' => 'portfolio',
    'portfolio_category' => 'social-media-marketing',
    'posts_per_page' => -1,
  )
  );
?>

<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>

  <h3><?php the_title(); ?></h3>

<?php endwhile; wp_reset_query(); ?>

I would like to replace the portfolio category with the results from the custom post type, so the user can select which taxonomy to display.

The code I have to pull in the Advanced custom field taxonomy is here:

<?php 

$term = get_field('portfolio_category');

if( $term ): ?>

  <h2><?php echo $term->slug; ?></h2>

<?php endif; ?>

Both bits of code work separately. I've tried running them both together like this:

<?php

$term = get_field('portfolio_category');

$loop = new WP_Query( array(
    'post_type' => 'portfolio',
    'portfolio_category' => 'echo $term->slug;',
    'posts_per_page' => -1,
  )
  );
?>

<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>

  <h3><?php the_title(); ?></h3>

<?php endwhile; wp_reset_query(); ?>

As well as a few other things, but I can't seem to get it to display anything... What am I doing wrong??


Solution

  • Change this

    'portfolio_category' => 'echo $term->slug;'
    

    To:

    'portfolio_category' => $term->slug
    

    You were passing the variable as a string instead of a variable.