使用分类法仅查询当前职位类型

时间:2015-06-17 作者:Allen

我有几个职位类型“课程”,“学院”有相同的分类“国家”。我用这个来获得单门课程的学期。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>\';
} 
?>
当我单击term时,它会得到所有具有“country”分类法的帖子类型。如何使用它仅获取当前的帖子类型。

2 个回复
最合适的回答,由SO网友:s_ha_dum 整理而成

If you look at WordPress\' available query variables, 你会注意到post_type. 您需要将其添加到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>\';
} 
参考文献:
https://developer.wordpress.org/reference/functions/add_query_arg/

SO网友:Bruno Monteiro

也许你可以试试这个:

<?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();
  }
}
?>
使用var_dump($tax_term) 您可以准确地验证可用的属性(名称、slug、ID、count等)-如果一切都按预期运行,那么所有这些属性都应该可用:

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

结束

相关推荐