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 block string 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"} /-->