Home › Forums › Front-end Issues › Attach uploads from post_content to post in frontend
Hi!
The problem is that files uploaded from frontend are not attached to post. I examined this solutions:
https://support.advancedcustomfields.com/forums/topic/acf_form-attachment-to-media-gallery/
https://support.advancedcustomfields.com/forums/topic/attach-images-created-in-front-end-form-to-custom-post/
But as I understood they work well only for specific fields, but not for post_content field.
Is there any solution to attach uploaded files in post_content (fe images), to post (update their post_parent)?
Thanks in advance!
No there isn’t, and it would be difficult to do so. You would need to parse the HTML in post_content to find the images and the image IDs added to the content preg_match_all() and a regular expression.
Here is an example of an image inserted into content
<img class="alignnone size-medium wp-image-140" src="http://domain.com/wp-content/uploads/2023/03/image.jpg" alt="" width="300" height="169" />
you can see that in the class the image ID of “140” is included.
This has not been tested, but something like might do it.
preg_match_all('/wp-image-(\d+)/', $string, $matches);
And you’re list of ID (as strings) would be found in $matches[1]
.
Thank you!
I tried this, but it failed:
function my_save_post( $post_id ) {
$my_content = get_field('post_content', $post_id);
if($my_content){
preg_match_all('/wp-image-(\d+)/', $content, $matches);
$imagatt = $matches[1];
foreach( $imagatt as $imagat ):
$post_to_update = array(
'ID' => $imagat,
'post_parent' => $post_id
);
wp_update_post( $post_to_update );
endforeach;
}
}
add_action('acf/save_post', 'my_save_post', 20);
I also tried
$my_content = $_POST['post_content'];
instead of
$my_content = get_field('post_content', $post_id);
In template I use:
<?php acf_form(array(
'post_id' => 'new_post',
'new_post' => array(
'post_type' => 'upr',
),
'post_title' => true,
'post_content' => true,
'submit_value' => 'Add item'
)); ?>
Can you help me? I think the solution is not so far…
Oh, of course $content means $my_content, but that’s not the reason.
Like I said, I don’t know if the regular expression is returning what I think it is because I have not tested it. I would output it to see
// temp line to test what is matched
var_dump($matches); exit;
Also, Post ID’s must be integers and $matches will contain strings if it’s returning anything
'ID' => intval($imagat),
You must be logged in to reply to this topic.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.