I would like to save data into ACF blocks via wp_insert_post() function.
My example data is a table, where ‘main_text’ might include new lines, single or double quotes, html tags like links.
I have a function to generate an ACF block and insert to $postData[‘post_content’]. However, my code doesn’t create new lines on the block.
$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 . ' /-->';
}
My ACF generated code (preview in the Admin Panel - Code editor):
<!-- 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"} /-->
1 Answer 1
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'
])
] );
answered Jul 27, 2023 at 4:52
Sheikh Ershad Munsuri
1322 silver badges4 bronze badges
Sign up to request clarification or add additional context in comments.
1 Comment
Matteor
It seems that it does not resolve the problem, I think the problem is how ACF reading generated JSON file. Seems like added \n between new lines not adding on the front. Generated code: prnt.sc/U2c2lc6tbLTA you can compare the code generated when I add block in the Admin panel: prnt.sc/SO0v5SXMKQqD . Also I'm not sure why md5() function we are using and both examples have different values.
Explore related questions
See similar questions with these tags.
default