Taxonomies: Parse image fields

If you use a theme or plugin that stores a taxonomy term (category?) image ID in the meta for the term, this snippet might help.

In the case of the snippet below, the Woodmart theme stores an image URL and an image ID in PHP serialized metadata for the pa_brand taxonomy.

The snippet will go through all terms in the taxonomies in bold below, find out if they have an image meta, unserialize and then analyze the array data. After broadcasting, the iamge meta is replaced with the equivalent image ID and URL values.

add_action( 'threewp_broadcast_collect_post_type_taxonomies', function( $action )
{
    // These are the taxonomies to parse.
    $taxonomies = [
        'category',
        'pa_brand',
    ];

    $bcd = $action->broadcasting_data;

    foreach( $bcd->taxonomy_term_meta->collection( get_current_blog_id() )->collection( 'terms' ) as $term_id => $term )
    {
        // Does this term have an image post meta key?
        $image = $term->get( 'image' );
        if ( ! is_array( $image ) )
            continue;

        $image = reset( $image );
        $image = maybe_unserialize( $image );

        // The meta must be an array.
        if ( ! is_array( $image ) )
            continue;

        // The array must contain an ID key.
        if ( ! isset( $image[ 'id' ] ) )
            continue;

        // The array must contain a URL key.
        if ( ! isset( $image[ 'url' ] ) )
            continue;

        // Add the id!
        $image_id = $image[ 'id' ];
        if ( ! $bcd->try_add_attachment( $image_id  ) )
            continue;

        if ( ! isset( $bcd->term_meta_image_url_id ) )
            $bcd->term_meta_image_url_id = ThreeWP_Broadcast()->collection();
        $bcd->term_meta_image_url_id->set( $term_id, $image );
        ThreeWP_Broadcast()->debug( 'Saved image/url/id: %s', $image[ 'id' ] );
    }
} );

add_action( 'threewp_broadcast_wp_update_term', function( $action )
{
    $bcd = $action->broadcasting_data;

    if ( ! isset( $bcd->term_meta_image_url_id ) )
        return;

    ThreeWP_Broadcast()->copy_attachments_to_child( $bcd );

    // We are only interested in the old term IDs we correctly parsed.
    $old_term_id = $action->old_term->term_id;

    $image = $bcd->term_meta_image_url_id->get( $old_term_id );

    // This is cheaper than a ->has() call, and then a get().
    if ( ! $image )
        return;

    $new_image_id = $bcd->copied_attachments()->get( $image[ 'id' ] );

    $image[ 'id' ] = $new_image_id;
    $image[ 'url' ] = ThreeWP_Broadcast()->update_attachment_ids( $bcd, $image[ 'url' ] );

    $new_term_id = $action->new_term->term_id;
    update_term_meta( $new_term_id, 'image', $image );
    ThreeWP_Broadcast()->debug( 'Updated term %s image/url/id: %s',
        $new_term_id,
        $image
    );
} );