基于非单一元数据获取帖子

时间:2021-12-02 作者:Lovor

I have meta data to custom post "event", registered as non-single, i.e., there is an array od metadata "terms" (it is not WordPress term, I just call it term, it is a record containing start date of the event, end date of event and possibly start and end time of the event.

register_meta(
    \'post\',
    \'term_definition\',
    [
        \'object_subtype\' => \'event\',
        \'type\' => \'object\',
        \'description\' => \'object with time data of the event\',
        \'single\' => false,
        \'auth_callback\' => __NAMESPACE__ . \'\\authentication\',
        \'sanitize_callback\' => \'sanitization\',
        \'show_in_rest\' => [
            \'schema\' => [
                \'type\' => \'object\',
                \'properties\' => [
                    \'ID\' => [
                        \'type\' => \'integer\'
                    ],
                    \'startDate\' => [
                        \'type\' => \'string\'
                    ],
                    \'endDate\' => [
                        \'type\' => \'string\'
                    ],
                    \'startTime\' => [
                        \'type\' => \'string\'
                    ],
                    \'endTime\' => [
                        \'type\' => \'string\'
                    ],
                ]
            ]
        ]
    ]
)

I want to get all posts of my custom type event, where startDate in metadata is after current datetime (or before current datetime). From documentation, it seems this is only possible for single, simple metadata, as described in the handbook. As a sidenote, I noticed that metadata created in this way get serialized and stored in the database like so:

meta_key: \'term_definition\'
meta_value: a:3:{s:9:"startDate";s:19:"2021-12-09T16:36:00";s:2:"ID";i:0;s:7:"endDate";s:19:"2021-12-10T16:36:00";}
1 个回复
最合适的回答,由SO网友:Tom J Nowell 整理而成

您是正确的,这对于序列化数据是不可能的。有一些黑客试图通过搜索序列化字符串的各个部分来绕过这个问题,但这些部分会抛出大量误报,并且无法排序。

通常,将结构化数据存储在单个元值中是一种反模式,您不能在meta_query 领域如果您必须存储它,请将其存储为JSON,但请记住您不能查询或对内容执行逻辑。(序列化的PHP值也会使您面临对象反序列化攻击,如果长度发生变化,在数据库上运行朴素的搜索替换查询时会中断)

这里的解决方案是将其分离为单独的原子post meta,至少5个,用PHP/JS进行排序,或者创建子post类型来表示事件,以便使用标准的日期时间列

相关推荐

如何让`wp-list-table`显示我在Custom-Post中的`Custom-Fields`

一切都好吗<我需要wp-list-table 也要显示custom-fields 在每个custom-post 我有,但我不知道如何做到这一点,在这幅图中,它显示了带有字段的表格:Title, Author and Publication Date: 我想要的是能够选择custom-fields 将出现,例如以下示例Title, Carta, Naipe, Author, and Date of Publication: