0

I'm trying to find a way to save an mp3 link in the_content to a custom field (using ACF).

Posts in the_content look like this:

http://feeds.soundcloud.com/stream/347813964-scott-johnson-27-tms-1361-pm.mp3

Description of the audio file

I can extract the mp3 link in my theme using preg_match_all but it would be a lot better to save the mp3 link to a custom field than using PHP to extract.

<?php $pattern = "/(http|https):\/\/.*\/(.*)\.(mp3|m4a|ogg|wav|wma)/";
$subject = get_the_content();
preg_match_all ($pattern, $subject, $matches);
echo $matches[0][0];?>

The above will show only the mp3 link. The code below is what I'm using in my theme's functions.php. I have an ACF textbox called audio_url in the editor that doesn't save anything, just a blank box when I save a post.

function save_url_link($post_id){
$pattern = "/(http|https):\/\/.*\/(.*)\.(mp3|m4a|ogg|wav|wma)/";
$subject = get_the_content($post_id);
preg_match_all ($pattern, $subject, $matches);
update_post_meta($post_id, 'audio_url', $matches[0][0]);}
add_action( 'save_post', 'save_url_link' );
  • pdate_post_meta is missing a u – Jacob Peattie Oct 23 '17 at 3:32
  • Accidentally removed it during spacing, is in original – Gregory Schultz Oct 23 '17 at 3:34
2

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.

  1. Now we are using the second parameter $post in the callback, and we're picking up the submitted post content via $post->post_content.

  2. add_action's fourth argument is the the number of arguments your callback will take. Default is 1. We are using 2 because we now have $post_id and $post.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.