0

I have several post types "Courses", "Institutes" having same taxonomy "country". I am using this to get term on single-courses.php

<?php
$terms = get_the_terms( $post->ID , 'country' ); 
foreach ( $terms as $term ) {
    $term_link = get_term_link( $term, 'country' );
    if( is_wp_error( $term_link ) )
    continue;
    echo '<a href="' . $term_link . '">' . $term->name . '</a>';
} 
?>

When I click term, it get all post types having "country" taxonomy. How can I use it to get ONLY CURRENT POST TYPE.

1

2 Answers 2

1

If you look at WordPress' available query variables, you will notice post_type. You will need to add that to your URL:

$terms = get_the_terms( $post->ID , 'category' ); 
foreach ( $terms as $term ) {
  $term_link = get_term_link( $term, 'category' );
  if( is_wp_error( $term_link ) ) 
  continue;
  $term_link = add_query_arg(
    array(
      'post_type' => $post->post_type
    ),
    $term_link
  );
  echo '<a href="' . $term_link . '">' . $term->name . '</a>';
} 

Reference:
https://developer.wordpress.org/reference/functions/add_query_arg/

0

Maybe you can try this:

<?php
$post_type = 'your_current_post_type_name';
$tax = 'your_taxonomy_name';
$tax_terms = get_terms($tax);
if ($tax_terms) {
  foreach ($tax_terms  as $tax_term) {
    $args=array(
      'post_type' => $post_type, // Here you will tell Wordpress only query on this post type
      "$tax" => $tax_term->slug,
      'post_status' => 'publish',
      'posts_per_page' => -1,
      'caller_get_posts'=> 1
    );

    $my_query = null;
    $my_query = new WP_Query($args);
    if( $my_query->have_posts() ) {
      while ($my_query->have_posts()) : $my_query->the_post(); ?>
            ...
        <?php
      endwhile;
    }
    wp_reset_query();
  }
}
?>

Using var_dump($tax_term) you can verify exactly what is available to use (name, slug, ID, count, etc) - if everything run as expected, all these attributes should be available to use:

stdClass Object
(
    [term_id] =>
    [name] =>
    [slug] =>
    [term_group] => 
    [term_order] => 
    [term_taxonomy_id] =>
    [taxonomy] =>
    [description] => 
    [parent] =>
    [count] =>
    [object_id] =>
)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.