我想通过 wp_insert_post() 函数将数据保存到 ACF 块中。
我的示例数据是一个表,其中“main_text”可能包含换行符、单引号或双引号、链接等 html 标签。
我有一个函数可以生成 ACF 块并插入 $postData[‘post_content’]。 但是,我的代码不会在块上创建新行。
$postData = array(
'post_type' => 'reports',
'post_status' => 'draft',
'post_title' => 'Post Title';
);
$postData['post_content'] = getPostContent();
$postID = wp_insert_post($postData);
function getPostContent() {
$dataToSave = [
'mode' => 'edit',
'name' => 'acf/pd-text',
'data' => [
'title' => 'Example Block Title',
'main_text' => 'This is the first line
This is the line
[custom-shortcode id="5" caption="Title"]
Another line with link <a href="">Link text</a>.'
]
];
$attrs = wp_json_encode( $dataToSave, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_QUOT | JSON_HEX_AMP | JSON_UNESCAPED_UNICODE );
$attrs = addslashes( $attrs );
return '<!-- wp:' . $name . ' ' . $attrs . ' /-->';
}
我的 ACF 生成的代码(在管理面板 - 代码编辑器中预览):
<!-- wp:acf/pd-text {"name":"acf/pd-text","data":{"title":"Example Block Title","main_text":"This is the first line\nThis is the line\n[custom-shortcode id=\u00225\u0022 caption=\u0022Title\u0022]\nAnother line with link \u003ca href=\u0022\u0022\u003eLink text\u003c/a\u003e."},"mode":"edit"} /-->
Try this code:
function setAcfGetBlock(
string $block,
array $fieldData
) {
$fields = [];
foreach($fieldData as $fieldKey => $fieldValue) {
$key = 'block_' . $block . '_' . $fieldKey;
$fields[$key] = $fieldValue;
$fields['_'.$key] = 'field_' . md5($key);
}
$json = [
'name' => 'acf/' . $block,
'data' => $fields,
'mode' => 'edit'
];
$fields = json_encode($json);
$acfJson = <<<ACFJSON
<!-- wp:acf/$block $fields /-->
ACFJSON;
return $acfJson;
}
so you can then do something like
wp_insert_post( [
'post_type' => 'job',
'post_status' => 'publish',
'post_title' => 'My Jobname',
'post_content' => setAcfGetBlock('title', [
'subtitle' => 'My subtitle'
])
] );