Is there a way to add, for example, an MP3 file to a WooCommerce product from PHP rather than from the dashboard panel?

Looking in the database I see that downloadable_files seems to be a serialized data field that handles this. But I wonder if there is a more straightforward, recommended way through the API? Something like $product->put_files()?


Create a metabox for the admin editor in single product. I use a plugin instead of trying to add to child theme or functions.

//add a woocommerce metabox to the product editor
add_action( 'woocommerce_product_options_general_product_data', 'plugin_add_audio_meta_box' );

function plugin_add_audio_meta_box()
{ ....
        <td class="file_url">
            <input type="text" class="input_text"
            placeholder="<?php esc_attr_e( "http://", 'plugin' ); ?>"
            value="<?php echo $plugin_fileurl; ?>" />

       <td class="file_url_choose" width="1%">
            <a href="#" class="button upload_file_button"
            data-choose="<?php esc_attr_e( 'Choose file', 'plugin' ); ?>"
            data-update="<?php esc_attr_e( 'Insert file URL', 'plugin' ); ?>">
            <?php echo str_replace( ' ', '&nbsp;', __( 'Choose file', 'plugin' ) ); ?></a>
.... }

function save_fields ...
update_post_meta( $post_id, ....

Then call the file wherever you need it on the front side:

            $attr = array(
                'src'      => strip_tags($plugin_fileurl),
                'loop'     => 'true',
                'autoplay' => '',
                'preload'  => 'none',

            echo '<div class="audio-player" itemprop="audio">' . wp_audio_shortcode( $attr ) . ' </div>';

            /* echo do_shortcode('[audio src="'.esc_url($plugin_fileurl).'"][/audio]'); */
| improve this answer | |

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.