Add Snippet To Project
Do you have a YouTube playlist that you want to incorporate into your WordPress website? You might think that embedding a single video is easy, but what about a whole playlist? In this article, we’ll show you how to embed a YouTube playlist and make it look great on your WordPress site – no coding required. Let’s begin!
function wpturbo_embed_youtube_playlist( $atts ) {
$atts = shortcode_atts( array(
'id' => '',
'width' => '100%',
'height' => '500px',
'autoplay' => 'false'
), $atts );
// Embed YouTube playlist
$output = '<iframe width="' . esc_attr( $atts['width'] ) . '" height="' . esc_attr( $atts['height'] ) . '" src="https://www.youtube.com/embed/videoseries?list=' . esc_attr( $atts['id'] ) . '&autoplay=' . esc_attr( $atts['autoplay'] ) . '" frameborder="0" allowfullscreen></iframe>';
return $output;
}
add_shortcode( 'youtube_playlist', 'wpturbo_embed_youtube_playlist' );
The wpturbo_embed_youtube_playlist()
function in this code snippet is used to generate the HTML code needed to embed a YouTube playlist in a WordPress post or page. This function is hooked into a WordPress shortcode, which allows you to create custom tags to insert predefined content.
The function uses the shortcode_atts()
function to set default values for the shortcode attributes. If a user does not specify a value for an attribute, the default value will be used instead. In this case, the default values are set to an empty id
value, a width
of 100%, a height
of 500px, and autoplay set to false.
The iframe
element is used to embed the YouTube playlist. The function concatenates the id
value specified in the shortcode with the YouTube playlist embed URL and appends any additional values for autoplay
, width
, and height
. The final output is an HTML iframe
element with the specified playlist embedded.
The esc_attr()
function is used to escape values of the shortcode attributes and ensure that they are secure for rendering in HTML. This helps to prevent security issues like cross-site scripting (XSS) attacks.
Lastly, the add_shortcode()
function is used to create the new shortcode tag youtube_playlist
and hook it to the wpturbo_embed_youtube_playlist()
function, so that the shortcode can be used in WordPress posts or pages.
In summary, the code snippet creates a custom shortcode that can be used to easily embed YouTube playlists in WordPress posts or pages, and takes care of setting default values and escaping values for security.