/** * Simple Add YouTube Video to WooCommerce Product * https://wpgenie.org * this code snippet goes to themes\child-theme\functions.php */ /** * 1. BACKEND: Add a Custom Meta Box for YouTube Video ID * */ add_action( 'add_meta_boxes', 'add_wc_youtube_video_meta_box' ); function add_wc_youtube_video_meta_box() { add_meta_box( 'wc_youtube_product_video', __( 'Product YouTube Video', 'woocommerce' ), 'render_wc_youtube_video_meta_box', 'product', 'side', // Places it in the sidebar near the Product Gallery 'low' ); } function render_wc_youtube_video_meta_box( $post ) { $video_id = get_post_meta( $post->ID, '_product_youtube_id', true ); wp_nonce_field( 'save_wc_youtube_video_meta', 'wc_youtube_video_nonce' ); echo '

'; echo ''; echo '

' . __( 'Paste only the 11-character video ID (the part after "v=" in the URL).', 'woocommerce' ) . '

'; } /** * 2. BACKEND: Save the YouTube Video ID when the product is saved */ add_action( 'woocommerce_process_product_meta', 'save_wc_youtube_video_meta' ); function save_wc_youtube_video_meta( $post_id ) { if ( ! isset( $_POST['wc_youtube_video_nonce'] ) || ! wp_verify_nonce( $_POST['wc_youtube_video_nonce'], 'save_wc_youtube_video_meta' ) ) { return; } if ( isset( $_POST['product_youtube_id'] ) ) { $video_id = sanitize_text_field( $_POST['product_youtube_id'] ); update_post_meta( $post_id, '_product_youtube_id', $video_id ); } } /** * 3. FRONTEND: Hook the YouTube Video above the Product Gallery * WooCommerce outputs the gallery at priority 20. Setting this to 15 pushes it directly above it. */ /** * Hook: woocommerce_single_product_summary. * * @hooked woocommerce_template_single_title - 5 * @hooked woocommerce_template_single_rating - 10 * @hooked woocommerce_template_single_price - 10 * @hooked woocommerce_template_single_excerpt - 20 * @hooked woocommerce_template_single_add_to_cart - 30 * @hooked woocommerce_template_single_meta - 40 * @hooked woocommerce_template_single_sharing - 50 * @hooked WC_Structured_Data::generate_product_data() - 60 */ add_action( 'woocommerce_single_product_summary', 'display_youtube_video_above_gallery', 15 ); function display_youtube_video_above_gallery() { global $product; if ( ! $product ) { return; } // Fetch the Video ID $video_id = get_post_meta( $product->get_id(), '_product_youtube_id', true ); // If an ID exists, output the responsive player if ( ! empty( $video_id ) ) { ?>