For some reason, your $subject
variable is empty when you call get_the_content($post_id)
.
When using save_post
hook, you can pass additional arguments like $post
and $update
to your callback.
For your case, you could use the second argument $post
to grab the post contents.
Code:
function save_url_link( $post_id, $post ){
$pattern = "/(http|https):\/\/.*\/(.*)\.(mp3|m4a|ogg|wav|wma)/";
$subject = $post->post_content;
preg_match_all ( $pattern, $subject, $matches );
update_post_meta( $post_id, 'audio_url', $matches[0][0] );
}
add_action( 'save_post', 'save_url_link', 10, 2 );
The above code uses the logic you implemented, with some differences.
-
Now we are using the second parameter
$post
in the callback, and we’re picking up the submitted post content via$post->post_content
. -
add_action
‘s fourth argument is the the number of arguments your callback will take. Default is1
. We are using2
because we now have$post_id
and$post
.