0

I have a function that strips an mp3 link from the_content and saves it a custom field called audio_url and then removes the mp3 link from the the_content. What I need help with is if the the_content has a new mp3 link and the custom field needs to be updated with the new mp3 link. I've tried so many options that it either won't update or it deletes the data written in the custom field

My function code:

function save_url_link( $post_id, $post ){
// only works if the post is an audio post format
if ( has_post_format('audio', $post_id)) {
// look for either http or https mp3, m4a, ogg, wav or wma files
$pattern = "/(http|https):\/\/.*\/(.*)\.(mp3|m4a|ogg|wav|wma)/";
// php the removes all except the mp3 link
preg_match_all($pattern,$post->post_content,$matches);
// saves the mp3 link to a string
$audio_raw = $matches[0][0];
// check if meta field is empty
if (get_post_meta( $post_id, 'audio_url', true ) == '') {
  // update the meta field
  update_post_meta( $post_id, 'audio_url', $audio_raw ); 
  // removes the save action
  remove_action('save_post', 'save_url_link', 10, 2);
  // update the content without the mp3 link
  wp_update_post(array('ID' => $post_id,'post_excerpt'=>$audio_raw,'post_content' => preg_replace('/(http|https):\/\/.*\/(.*)\.(mp3|m4a|ogg|wav|wma)/', "", $post->post_content)));  
// close and save
};}}
add_action( 'save_post', 'save_url_link', 10, 2 );

1 Answer 1

2

I suppose it deleted the value when you had no URL in the content, so $audio_raw was empty.

if ($audio_raw && get_post_meta( $post_id, 'audio_url', true ) != $audio_raw) {
  // update the meta field
  update_post_meta( $post_id, 'audio_url', $audio_raw ); 
}

checks that $audio_raw isn't false/null/empty and that $audio_raw isn't the same as the string currently in audio_url.

BTW, I'm pretty sure

remove_action('save_post', 'save_url_link', 10, 2);

Doesn't really to anything, since you're already in that hook when you're removing the hook from save_post. It won't run twice, so no need to remove it.

2
  • I added the remove_action because I have having time-out issues and that fixed it. Commented Oct 23, 2017 at 23:41
  • That's strange, but hey, whatever works! Does the audio_url-update work for you? Commented Oct 23, 2017 at 23:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.