Halloween Sale 15% off Ends in See the plans
PHP

Product Video Tab

Adds a "Video" field to products and shows the video (YouTube, Vimeo or an uploaded MP4) in its own product tab.

Don’t have WPIDE yet? Install it on your site

Code

add_action( 'woocommerce_product_options_general_product_data', function () {
    global $product_object;

    woocommerce_wp_text_input( array(
        'id'          => '_wpide_video_url',
        'label'       => 'Video URL',
        'type'        => 'url',
        'placeholder' => 'https://www.youtube.com/watch?v=...',
        'value'       => $product_object instanceof WC_Product ? $product_object->get_meta( '_wpide_video_url' ) : '',
    ) );
} );

add_action( 'woocommerce_admin_process_product_object', function ( $product ) {
    // phpcs:ignore WordPress.Security.NonceVerification -- WooCommerce verifies the product save nonce.
    if ( isset( $_POST['_wpide_video_url'] ) ) {
        $product->update_meta_data( '_wpide_video_url', esc_url_raw( wp_unslash( $_POST['_wpide_video_url'] ) ) );
    }
} );

add_filter( 'woocommerce_product_tabs', function ( $tabs ) {
    global $product;

    $url = $product instanceof WC_Product ? $product->get_meta( '_wpide_video_url' ) : '';

    if ( $url ) {
        $tabs['wpide_video'] = array(
            'title'    => 'Video',
            'priority' => 15,
            'callback' => function () use ( $url ) {
                if ( preg_match( '/\.(mp4|webm|ogv)(\?.*)?$/i', $url ) ) {
                    echo wp_video_shortcode( array( 'src' => esc_url( $url ) ) ); // phpcs:ignore WordPress.Security.EscapeOutput
                    return;
                }

                $embed = $GLOBALS['wp_embed']->shortcode( array(), esc_url( $url ) );
                echo '<div class="wpide-video-tab">' . $embed . '</div>'; // phpcs:ignore WordPress.Security.EscapeOutput -- oEmbed output.
            },
        );
    }

    return $tabs;
} );

Notes

Paste a YouTube or Vimeo link or a media library MP4 URL; WordPress caches the embed after the first view.

How to add this snippet

  1. Install WPIDE on your WordPress site (it is free) and open Code Snippets.
  2. Use snippet above adds it from the library in one click. Or copy the code into a new snippet with the same code type.
  3. It is added inactive: review the code and settings, then switch it on.

Have a snippet worth sharing?

Publish it to the library from WPIDE or right here. Sign in with any WordPress site that runs WPIDE, free or Pro. Public snippets are reviewed by the WPIDE team before they appear.

Which site should get this snippet?

Enter the address of your WordPress site. WPIDE opens there in a new tab with the snippet ready to review and save.

Remembered in this browser only, so you are asked once.

Report this snippet

Tell the WPIDE team what is wrong: broken code, something harmful, spam or copied work.