【问题标题】:Catchable fatal error: Object of class stdClass could not be converted to string in line 125...... in WordPress可捕获的致命错误:在 WordPress 中,stdClass 类的对象无法在第 125 行转换为字符串......
【发布时间】:2025-12-13 23:20:04
【问题描述】:

我正在尝试过滤掉帖子类型的标题,我得到了这个

可捕获的致命错误:stdClass 类的对象无法在第 125 行转换为字符串

这是我使用的代码...

add_filter('wpseo_title', 'vehicle_listing_title', 10, 1);
function vehicle_listing_title( $title ) {
    global $post;
    if ( get_post_type() == 'vehicles' ){

       $model = get_queried_object('vehicle_model');
       $location = get_queried_object('vehicle_location');
       $title = $model . "used cars for sale in" . $location .'on'. get_bloginfo('name');  <---- this is line 125
    }

    return $title;
    }

【问题讨论】:

  • 该死,顾名思义,get_queried_object 必须返回一个对象,您只需将其与字符串连接起来,我想不会实现 __toString。试试var_dump($model, $location)看看吧。

标签: php wordpress filter fatal-error


【解决方案1】:

get_queried_object() 不允许参数。

试试这个:

$post = get_queried_object();
$location = $post->post_title;

也许你的vehicle_modelvehicle_location是元字段,那么你必须使用get_post_meta()函数

您是否使用任何插件来扩展您的帖子字段,例如 Advance-Custom-Fields?

编辑:看 cmets,你使用 ACF 插件。所以你的代码应该是:

add_filter('wpseo_title', 'vehicle_listing_title', 10, 1);
function vehicle_listing_title( $title ) {
    if ( get_post_type() == 'vehicles' ){

       $model = get_field('vehicle_model');
       $location = get_field('vehicle_location');
       $title = $model . "used cars for sale in" . $location .'on'. get_bloginfo('name'); 
    }

    return $title;
}

【讨论】:

  • 您的两个建议都只返回了“网站名称上出售的二手车”,没有帖子标题。是的,我正在使用 ACF 插件。
  • 那么您可以使用get_field('vehicle_model', $postId); 轻松获取值,请查看文档:advancedcustomfields.com/resources/get_field
  • 好的,我已经尝试过了,它还返回了没有帖子标题的过滤标题。我也试过$vehicle_location = get_queried_object_id('vehicle_location') 它返回760used cars for sale in760on sitename,这似乎更接近所需的结果。您知道如何将其从 id 更改为名称吗?
  • 始终查看系统文档。你不能在get_quieried_object_id()上加个参数
  • 啊,是的,你是对的,我查过了。现在真的很混乱
【解决方案2】:

根据 $location 对象的内容,您可能会使用 print_r() 将其添加到标题中。

       $title = print_r($model, true) . "used cars for sale in" . print_r($location, true) .'on'. get_bloginfo('name');  <---- this is line 125

true 告诉函数返回结果而不是回显它。

如果您的对象具有需要从内部获取数据的内部结构,那么您可以执行以下操作:

   $title = $model[0] . "used cars for sale in" . $location[0] .'on'. get_bloginfo('name');  <---- this is line 125

var_dump($location); var_dump($model); 将输出对象的全部内容,以便您查看其结构。只需将 [0] 中的“0”替换为您想要的项目的键(或多个键 IE $model[0][0][0])。

此外,我看到您已经在此处拥有了 post 对象 ($post)。也许您可以窥视该对象内部,看看模型和位置是否在那里? var_dump($post);

【讨论】:

  • 好的,我试过了,结果还是一样。这就是我得到的 'print_r()' 'stdClass( [term_id] => 760 [name] => london [slug] => London [term_group] => 0 [term_taxonomy_id] => 760 [taxonomy] => vehicle_location [description] => [parent] => 19[count] => 0[filter] => raw) 二手车 instdClass Object ([term_id] =>760 [name] => London [slug] => London [ term_group] => 0 [term_taxonomy_id] => 760 [taxonomy] => vehicle_location [description] => [parent] => 19 [count] => 0 [filter] => raw)on sitename'
最近更新 更多