Your code:
$cat_data = get_option("category_$cat_id");
if ( isset($cat_data['extra1'] ) ){
echo do_shortcode('[videojs youtube="'.$cat_meta['extra1'].'" width="699" height="269" preload="auto" loop="true" autoplay="false" controls="false" class="responsive-video"]');
}
There’s a number of things you’re not doing or could do better here:
- You never check if the option exists, if
get_option
doesn’t find anything and returns a value offalse
your code may fatal error and crash - You’re relying on the
videojs
shortcode, but you can remove this dependency by using the oembed functionality that comes with WordPress. Did you know if you place a youtube URL in content on a line by itself, it’s auto-magically converted into video player? - You never check that the URL is indeed a URL, e.g. if the URL was:
"]<script>alert('hacked');</script>[sldfjknv attr="
, there’s a chance this could result in unescaped insecure javascript running on the frontend - If said plugin or shortcode isn’t present the functionality will fail with no fallback
- It doesn’t account for empty values or strings of spaces, ” ” is not a valid youtube URL, but it is a valid string, and will generate an invalid shortcode
- If
$cat_id
is replaced with a variable that isn’t a number it could have unexpected consequences, and is a possible route to sql injection
With this in mind, lets refactor:
$data = get_option( 'category_'.$cat_id );
// does the object exist?
if ( $data !== false ) {
// empty checks if the value is set, and also checks if it has something in it, not just spaces
if ( !empty( $data['extra1'] ) ) {
$url = $data['extra1'];
// URLs are URLs, lets escape this URL so that nothing nasty is passed along
$url = esc_url( $url );
// grab the embed html using oembed ( it has a second argument to specify width and height but it should be unnecessary )
$embed = wp_oembed_get( $url );
// set up a fallback
if ( $embed != false ) {
$embed = '<a href="'.$url.'">'.$url.'</a>';
}
echo $embed;
}
}
The new version checks the values are what they need to be, escapes the values, and uses the well tested WordPress Core APIs rather than a 3rd party. Responsiveness should be taken care of by your theme/plugins CSS. it also falls back to a hyperlink if the embed fails for whatever reason.