Home > database >  how to comma separate the taxonomy terms so it could be included dynamically in the tax query
how to comma separate the taxonomy terms so it could be included dynamically in the tax query

Time:03-31

I have managed to return the taxonomies that have been selected for a post however, these are returned as one appended list eg covid1covid2covid3. I want to be able to separate these out covid1, covid2, covid3 (not returning the last comma) so that I can use it in my tax query which would return related post dynamically based on these taxonomies. See my code below

  $currentID = get_the_ID();
  $post_terms = get_the_terms($currentID, 'vocabulary_1');

  foreach ($post_terms as $post_term) {
      $postTerm = $post_term->slug;  
  }

  $args1 = array(
    'post_type' => 'cme-education',
    'posts_per_page' => '1',
    'post_status' => 'publish',
    'orderby'=>'rand',

    'tax_query' => array(
        array(
            'taxonomy' => 'vocabulary_1',
            'field'    => 'slug',
            'terms'    => array($postTerm),
            'operator' => 'IN',
            'order' => 'ASC'
        )
    )
);

CodePudding user response:

The issue is in $postTerm. First make it array:

$postTerm = [];

then store terms in it, like this:

foreach ($post_terms as $post_term) {
    $postTerm[] = $post_term->slug;
}

Here is the complete code:

$currentID  = get_the_ID();
$post_terms = get_the_terms($currentID, 'vocabulary_1');
$postTerm   = [];
foreach ($post_terms as $post_term) {
    $postTerm[] = $post_term->slug; 
}
$args1 = array(
    'post_type'         => 'cme-education',
    'posts_per_page'    => '1',
    'post_status'       => 'publish',
    'orderby'           =>'rand',
    'tax_query'         => array(
        array(
            'taxonomy'  => 'vocabulary_1',
            'field'     => 'slug',
            'terms'     => $postTerm,
            'operator'  => 'IN',
            'order'     => 'ASC'
        )
    )
);
  • Related