我正在扩展Woocommerce产品CSV导入功能以导入更多数据。
我插入了一个包含2个元数据、一个字符串(URL)和一个bool的CPT,插入的post\\u meta被弄乱了。它为应该有布尔值的元插入一个数组。
代码快照:
$link = array(
\'url\' => $url // string
\'caption\' => $caption // string
\'hide\' => $hide // bol
$meta_input = array(
\'ct_external_link_url\' => $link[\'url\']
);
if( isset($link[\'hide\']) ) {
$meta_input += [\'ct_hide_from_frontent\' => $link[\'hide\']];
}
$postarr = array(
\'post_title\' => $link[\'caption\'],
\'post_type\' => \'ct_external_link\',
\'post_status\' => \'publish\',
\'post_excerpt\' => $link[\'caption\'],
\'meta_input\' => $meta_input
);
write_log("Args to insert external link post:"); // write_log ouputs to debug.txt
write_log($postarr);
$external_link_id = wp_insert_post($postarr);
$external_link = get_post($external_link_id, \'ARRAY_A\');
if( !is_null($external_link)) {
write_log("External link post:");
write_log($external_link);
write_log("External link post meta:");
$meta = get_post_meta($external_link_id);
write_log($meta);
}
由于我在写日志,这些日志如下所示:
[15-Mar-2019 10:33:45 UTC] Args to insert external link post:
[15-Mar-2019 10:33:45 UTC] Array
(
[post_title] => VÃdeo 1
[post_type] => ct_external_link
[post_status] => publish
[post_excerpt] => VÃdeo 1
[meta_input] => Array
(
[ct_external_link_url] => https://www.youtube.com/watch?v=F0IbjVq-fgs&ab_channel=CollegeMusic
[ct_hide_from_frontent] => 1
)
)
[15-Mar-2019 10:33:45 UTC] External link post meta:
[15-Mar-2019 10:33:45 UTC] Array
(
[ct_hide_from_frontent] => Array
(
[0] => 1
)
)
请注意,虽然键“ct\\u hide\\u from\\u front”的值是meta\\u输入中的布尔值,但它是作为数组从post\\u meta输出的。为什么?
谢谢
SO网友:Gonçalo Figueiredo
所以我最后只是在插入帖子后添加了meta,这不会给出任何错误。它绕过了问题,但没有解释它。。。
$postarr = array(
\'post_title\' => $link[\'caption\'],
\'post_type\' => \'ct_external_link\',
\'post_status\' => \'publish\',
\'post_excerpt\' => $link[\'caption\'],
);
$external_link_id = wp_insert_post($postarr);
if( !empty($external_link_id) ) {
add_post_meta($external_link_id, \'ct_external_link_url\', $doc[\'file\'], true);
if( isset($doc[\'hide\']) ) {
add_post_meta($external_link_id, \'ct_hide_from_frontent\', $doc[\'hide\']);
}
}