'不能将 stdClass 类型的对象用作数组'使用 WordPress

发布于 2024-11-10 13:01:15 字数 1177 浏览 0 评论 0原文

我正在尝试检索 WordPress 帖子内标签的 slug,现在可以使用

$tag = wp_get_post_tags($post->ID);

Wordpress Docs

通过使用这个,你应该得到像这样返回的数据...

Array
(
   [0] => stdClass Object
       (
           [term_id] => 4
           [name] => tag2
           [slug] => tag2
           [term_group] => 0
           [term_taxonomy_id] => 4
           [taxonomy] => post_tag
           [description] => 
           [parent] => 0
           [count] => 7
       )

   [1] => stdClass Object
       (
           [term_id] => 7
           [name] => tag5
           [slug] => tag5
           [term_group] => 0
           [term_taxonomy_id] => 7
           [taxonomy] => post_tag
           [description] => 
           [parent] => 0
           [count] => 6
       )

)

现在我想要的是第一个项目的slug,应该如下所示

$tag[0]['slug']

但是通过这样做我收到此 php 错误:

不能将 stdClass 类型的对象用作 数组

可以告诉我我在这里做错了什么吗?获取数据的最佳方法是什么

I am trying to retrieve the slug for a tag inside a wordpress post, now its possible to get all tag info using

$tag = wp_get_post_tags($post->ID);

More info on this on the Wordpress Docs

By using this you should get data returned like this...

Array
(
   [0] => stdClass Object
       (
           [term_id] => 4
           [name] => tag2
           [slug] => tag2
           [term_group] => 0
           [term_taxonomy_id] => 4
           [taxonomy] => post_tag
           [description] => 
           [parent] => 0
           [count] => 7
       )

   [1] => stdClass Object
       (
           [term_id] => 7
           [name] => tag5
           [slug] => tag5
           [term_group] => 0
           [term_taxonomy_id] => 7
           [taxonomy] => post_tag
           [description] => 
           [parent] => 0
           [count] => 6
       )

)

Now what I want is the slug for the first item which should be as follows

$tag[0]['slug']

However by doing so I recieve this php error:

Cannot use object of type stdClass as
array

Can someone tell me what I'm doing wrong here? and whats the best way to get the slug data

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

柠檬 2024-11-17 13:01:15

请注意,该数组包含对象stdClass的实例),而不是其他数组。所以语法是:

$tag[0]->slug

Note that the array contains objects (instances of stdClass), not other arrays. So the syntax is:

$tag[0]->slug
花桑 2024-11-17 13:01:15

另一个选择应该是显式地将 $tag[0] 转换为数组:

$t = (array)$tag[0];
$t["slug"] = ...

但无法让它工作

Another option should be to explicitly cast $tag[0] into an array:

$t = (array)$tag[0];
$t["slug"] = ...

Can't get it to work though

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文