【问题标题】:How to get taxonomy term name from a queried object如何从查询对象中获取分类术语名称
【发布时间】:2017-02-15 17:58:51
【问题描述】:

所以我正在努力实现以下目标。

到目前为止我的代码..

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. 这段代码导致$location & $model 是一个包含以下term_id =>,name=>,slug=>,term_group=>,etc 的对象,所以我想得到它的name 部分。
    我该怎么做?

  2. 即使没有任何帖子分配给查询的分类,我必须在代码中添加什么才能仍然返回修改后的$title

【问题讨论】:

  • 要从对象中获取属性,请使用 $object->property。在你的情况下$location->name。不确定您在第 2 点中的意思。
  • 好的,但是我把它放在代码的什么地方呢?我在第 2 点中想说的是,上面的代码仅在列出汽车时才有效。即使还没有任何列表,我希望代码仍然有效。我希望这是有道理的。

标签: php wordpress filter custom-taxonomy taxonomy-terms


【解决方案1】:

将您的代码更改为:

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;
}

基本上,您需要使用 IF 来构建您的标题,以检查是否可以获得模型和位置的术语数组。此外,wp_terms() 返回一个术语数组的数组,因此您还需要使用[0] 索引获取结果的第一个元素,然后链接['name'] 索引以获取术语的名称。

【讨论】:

  • 根据文档,get_the_terms 返回一个对象数组。这意味着你不能使用['name'],你必须使用->name
  • 好的,我试过了。它仍然不起作用。代码返回Fatal error: cannot use object of type stdClass as array in functions.php
  • 抱歉,我没有检查编辑后的代码。现在可以了。非常感谢。这给我留下了第 2 点。所以会发生什么,当帖子类型中有 nothing found 时,之前的标题设置仍然显示。我希望您的代码即使在 nothing found 时也能正常工作。这可能吗?或者这就是它应该是的样子
  • 要做到这一点,只需删除 if ( get_post_type() == 'vehicles' ){ 及其对应的 } 右括号,以及现在重复的 return $title; 语句。但是,我建议不要这样做,因为它会使您所有页面/帖子的所有标题成为“[博客名称]上出售的二手车”。最好只为“车辆”帖子类型执行此操作,就像您目前所做的那样。
  • 啊,我明白了。我宁愿保持原样。
猜你喜欢
  • 2017-09-20
  • 2020-02-08
  • 1970-01-01
  • 2017-07-26
  • 2021-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-09
相关资源
最近更新 更多