I want to add a pdf to a post. So I created a new file field. But when you want to publish my custom posttype. The url is alway ” when you press again on the update button the url is filled in? How is this possible? Am I using th right hooks? or right fields?
This is my code for saving the url of the pdf in the content.
function save_mytype( $content ) {
global $post;
if( isset($post) && get_post_type( $post->ID ) == ‘mytype’ ){
$file = get_field(‘pdf’);
$url = $file[‘url’];
if($url != ”){
$content[‘post_content’] = “[flipbook pdf=\””.$url.”\” theme=\”light\”]”;
//createNewsItem($post);
}else{
$content[‘post_content’] = “Something is wrong”;
}
}
return $content;
}
add_filter( ‘wp_insert_post_data’, ‘save_mytype’);
You are trying to get the value of the field before ACF has saved that value. You need to run a function after ACF is done saving so that there is a value to get. You do this by using acf/save_post https://www.advancedcustomfields.com/resources/acf-save_post/
function save_mytype($post_id) {
if (get_post_type($post_id) == 'mytype' ){
$file = get_field('pdf', $post_id);
$url = $file['url'];
$post = array(
'ID' => $post_id
);
if ($url != '') {
$post['post_content'] = '[flipbook pdf"'.$url.'" theme="light"]';
//createNewsItem($post);
}else{
$post['post_content'] = 'Something is wrong';
}
// remove filter to avoid infinite loop
remove_filter('acf/save_post', 'save_mytype');
wp_update_post($post);
add_action('acf/save_post', 'save_mytype');
}
}
add_action('acf/save_post', 'save_mytype');
Thank you so much!! You saved me from a minor headache!