---
tags:
  - wordpress
  - shortcode
  - php
  - optimization
  - video
title: Creating a Reusable Video Façade Shortcode
---

# Creating a Reusable Video Façade Shortcode

Manually pasting the HTML structure for the [[wordpress-video-optimization|Video Façade]] every time you want to embed a video is tedious and error-prone.

By wrapping the logic in a **Shortcode**, you can make it easy for editors to insert optimized videos using a simple tag like `[video_facade id="..."]`.

## 1. The PHP Shortcode Function

Add the following code to your theme's `functions.php` file or a custom plugin.

```php
/**
 * Shortcode: [video_facade id="VIDEO_ID"]
 */
function my_video_facade_shortcode( $atts ) {
    // 1. Extract attributes and set defaults
    $atts = shortcode_atts( array(
        'id' => '', // The YouTube Video ID
    ), $atts, 'video_facade' );

    // 2. Safety check: If no ID is provided, return nothing
    if ( empty( $atts['id'] ) ) {
        return '';
    }

    // 3. Start Output Buffering
    ob_start();
    ?>
    
    <!-- The Façade HTML Structure -->
    <div class="video-facade" data-youtube-id="<?php echo esc_attr( $atts['id'] ); ?>">
        <img src="https://i.ytimg.com/vi/<?php echo esc_attr( $atts['id'] ); ?>/maxresdefault.jpg" 
             alt="Play Video" 
             loading="lazy" 
             class="video-thumbnail"
             width="560" height="315"> <!-- Add dimensions to prevent CLS -->
        <div class="play-button"></div>
    </div>

    <?php
    // 4. Return the buffer
    return ob_get_clean();
}
add_shortcode( 'video_facade', 'my_video_facade_shortcode' );
```

## 2. Usage in the Editor

Now, anywhere in WordPress (Classic Editor, Gutenberg Shortcode Block, or Elementor), you can simply type:

```text
[video_facade id="dQw4w9WgXcQ"]
```

This will automatically render the optimized image placeholder.

## 3. Conditional Asset Loading (Advanced)

To be extremely efficient, you should only load the CSS and JS for the video player if the shortcode is actually present on the page.

```php
function my_enqueue_video_assets() {
    global $post;
    
    // Check if the post content contains the shortcode
    if ( is_a( $post, 'WP_Post' ) && has_shortcode( $post->post_content, 'video_facade' ) ) {
        wp_enqueue_style( 'video-facade-css', get_template_directory_uri() . '/assets/css/video-facade.css' );
        wp_enqueue_script( 'video-facade-js', get_template_directory_uri() . '/assets/js/video-facade.js', array(), '1.0', true );
    }
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_video_assets' );
```

## Related Guides
*   [[wordpress-video-optimization|Optimizing Video Embeds with the Façade Pattern]]
*   [[wordpress-request-optimization|Mastering HTTP Requests]]
*   [[wordpress-acf-video-block|Converting Shortcodes to ACF Blocks: The Video Façade Example]]