Wordpress提供了一种使用XML导入和导出其数据的简便方法。这是通过基于GUI的内置导入器完成的。但是,我想做的是能够从主题中导入某些XML文件(在激活时或在执行函数后)。
我的情况:虽然有一些插件可以为您创建虚拟内容,但我找不到任何方法来做我要做的事情-导入存储在XML文件中的一组ACF字段。
有什么办法吗?
更新:此功能旨在处理XML数据,并且仅限于版本4的ACF。ACF5将其字段导出为JSON数据。
该解决方案变成了Wordpress插件。
这是我的问题的解决方案。
function insert_acf_field( $xml_string, $allow_duplicates = false ) {
// Parse ACF post's XML
$content = simplexml_load_string( $xml_string, 'SimpleXMLElement', LIBXML_NOCDATA);
// Parse XML post attributes containing fields
$wp_post_attributes = $content->channel->item->children('wp', true);
# Copy basic properties from the exported field
$wp_post_data = array(
'post_type' => 'acf',
'post_title' => $content->channel->item->title,
'post_name' => $wp_post_attributes->post_name,
'post_status' => 'publish',
'post_author' => 1
);
$the_post = get_page_by_title($content->channel->item->title, 'OBJECT', 'acf');
# Execute only if doesn't exist already
if ( !$the_post || $allow_duplicates == true ) {
$post_id = wp_insert_post( $wp_post_data );
}
else {
$post_id = $the_post->ID;
}
$wp_post_meta = $content->channel->item->children('wp', true);
if( $wp_post_meta ) {
foreach ( $wp_post_meta as $row) {
// Choose only arrays (postmeta)
if( count($row) > 0) {
// using addlashes on meta values to compensate for stripslashes() that will be run upon import
update_post_meta( $post_id, $row->meta_key, addslashes( $row->meta_value ) );
}
}
}
}
使用方法如下:
函数期望至少$xml_string
传递参数。它应包含在导出ACF字段(acf
类型后)时由ACF插件生成的XML文件的内容。
该函数将尝试创建一个新的ACF帖子,除非已经存在一个新的ACF帖子,然后使用字段填充它。要插入多个具有相同标题的字段(克隆),则应将其true
作为第二个参数传递。
还有一些问题有待解决,但是当前状态下的功能应该可以使用
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句