dongzaocheng3214 2017-02-15 00:14
浏览 53
已采纳

如何从查询的对象中获取分类术语名称

So I'm trying to achieve the following.

My code so far..

add_filter('wpseo_title', 'vehicle_listing_title');
function vehicle_listing_title( $title ) 
{
  if ( get_post_type() == 'vehicles' )
  {
    $location = get_the_terms($post->ID, 'vehicle_location');
    $model = get_the_terms($post->ID, 'vehicle_model');
    $title = $model . 'used cars for sale in' . $location .'on'. get_bloginfo('name');
  }
  return $title;
}
  1. This code results in $location & $model being an object containing the following term_id =>,name=>,slug=>,term_group=>,etc so I want to get the name part of it.
    How do I do that?

  2. What do I have to add to the code to still return the modified $title even when there aren't any posts assigned to the queried taxonomies?

  • 写回答

1条回答 默认 最新

  • dongshan4878 2017-02-15 02:02
    关注

    Change your code to this:

    add_filter('wpseo_title', 'vehicle_listing_title');
    
    function vehicle_listing_title( $title ) 
    {
      if ( get_post_type() == 'vehicles' )
      {
        $location = get_the_terms($post->ID, 'vehicle_location');
        $model = get_the_terms($post->ID, 'vehicle_model');
        $title = '';
    
        if($model && $model[0]) $title .= $model[0]->name . ' used';
        else $title .= 'Used';
    
        $title .= ' cars for sale';
    
        if($location && $location[0]) $title .= ' in ' . $location[0]->name;
    
        $title .= ' on ' . get_bloginfo('name');
    
        return $title;
      }
    
      return $title;
    }
    

    Basically, you need to construct your title using IF's to check if the terms array could be obtained for the model and the location. Also, wp_terms() returns an array of term arrays, hence why you also need to obtain the first element of the result using a [0] index, and then chaining the ['name'] index to get the name of the term.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题