Add Snippet To Project
Are you having trouble getting your videos to display perfectly centered on your WordPress site? It’s a common problem that can make your site look unprofessional. But don’t worry – in this article, we’ll show you how to easily center your videos in WordPress. Whether you’re a beginner or experienced user, you’ll be able to follow along with our step-by-step guide. Let’s get started!
I apologize, but the code snippet I provided earlier was not correct. Here's the correct one:
function wpturbo_center_video( $html ) {
$doc = new DOMDocument();
$doc->loadHTML( '<div>' . $html . '</div>' );
$iframe = $doc->getElementsByTagName( 'iframe' )->item(0);
if ( $iframe ) {
$iframe->setAttribute( 'style', 'display: block; margin: 0 auto;' );
$html = $doc->saveHTML( $iframe );
}
return $html;
}
add_filter( 'embed_oembed_html', 'wpturbo_center_video', 10, 3 );
The code snippet provided is a WordPress plugin that centers embedded videos on posts and pages. The wpturbo_center_video()
function is a filter callback that modifies the output generated by the embed_oembed_html
filter. The filter is applied to all video embeds in WordPress, including those from YouTube, Vimeo, and other video hosting services.
The wpturbo_center_video()
function extracts the iFrame element from the embed code generated by the oEmbed service. It then applies a CSS style to center the iFrame within its container by adding display: block;
and margin: 0 auto;
to its style attribute.
$doc = new DOMDocument();
$doc->loadHTML( '<div>' . $html . '</div>' );
$iframe = $doc->getElementsByTagName( 'iframe' )->item(0);
if ( $iframe ) {
$iframe->setAttribute( 'style', 'display: block; margin: 0 auto;' );
$html = $doc->saveHTML( $iframe );
}
Finally, the function returns the modified embed code as a HTML string. This modified code is then displayed on the website instead of the original embed code.
return $html;
By adding this code to your WordPress site, your videos will be centered without you having to modify the code for each individual video.