Search code examples
wordpressadvanced-custom-fields

Wordpress update custom fields ACF programmatically when posts are imported


I am faced with a singular issue.

I have a plugin that syncs the RSS feed to posts (of category episode) in wordpress.

This plugin does not retrieve the duration of the episode so I thought I would do it myself, the plugin updates 2 episodes a month so not too much stress.

Took me hours to put together the following code in my theme's functions.php.

Every episode post has ACF Custom fields attached with duration/shownotes etc., so the idea is once the importer fetches the monthly episode, this would get the duration automatically and populate the relative ACF Field.

Here's the code:

function get_stream_from_audio_src($string){

    preg_match_all('#\bhttps?://[^\s()<>]+(?:\([\w\d]+\)|([^[:punct:]\s]|/))#', $string, $match);
    $stream_url = substr($match[0][0], 0, strpos($match[0][0], "mp3")+3);

    return $stream_url;
}

function run_after_saving_episode( $post ) {

    global $post;

    if (empty(get_post_meta($post->ID, 'duration', true))) {
        $clean_url = get_stream_from_audio_src(get_post_meta($post->ID, 'stream_id', true));
        $duration = get_MP3_Duration($clean_url);
        update_post_meta($post->ID, 'duration', $duration);
    }
}

add_action( 'acf/save_post', 'run_after_saving_episode',25,1 );

All works fine if I save / update manually in the admin, but the episode importer doesn't seem to trigger acf/save_post.

Am I missing something?

Thanks y'all!


Solution

  • Check if there is an action in the RSS importer from where you can call your own functin run_after_saving_episode.

    <?php
    
    add_action( PODCAST_IMPORTER_SECONDLINE_ALIAS . '_feed_item_imported', function( $feed_item_class ) {
        // Your logic here to get your $duration
    
        // Sanitzie the data
        $duration = podcast_importer_secondline_sanitize_feed_value( $duration );
    
        // Update the post meta
        update_post_meta( $feed_item_class->current_post_id, 'duration', $duration);
    });
    
    

    https://plugins.trac.wordpress.org/browser/podcast-importer-secondline/trunk/app/Helper/Importer/FeedItem.php#L227

    There are a bunch of variables available in the $feed_item_class, like $feed_item_class->audio_url and other which you might can use and find here above in the __construct() https://plugins.trac.wordpress.org/browser/podcast-importer-secondline/trunk/app/Helper/Importer/FeedItem.php#L47

    Remember to replace $this with $feed_item_class in your PHP code.