I am new to WordPress development. Currently I am trying to make an widget to embed video from youtube. My plan is an admin or an author will just give the video id and the video will be in widget area.
My Codes are following:
index.php
<?php
/*
Plugin Name: Youtube
Plugin URI: imonislam.com
Author: smartrahat
Author URI: imonislam.com
Description: This plugin will embed youtube video on sidebar or any widget location you want.
Version: 1.0
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the license or
(at your option) any later version.
This program is distributes in hope that it will be useful, but without
any warranty; without even the implied warranty of MERCHANTABILITY or
FITNESS for a PARTICULAR PERSON. See the GNU General Public License
for more details.
You should have receive a copy of GNU General Public License,
if not, see http://www.gnu.com/licenses/
*/
require_once 'youtube.php';
function register_youtube_widget(){
register_widget('youtube');
}
add_action('widgets_init','register_youtube_widget');
youtube.php
<?php
class youtube extends WP_Widget{
public function __construct()
{
parent::WP_Widget(
'youtube',
__('Youtube'),
[
'description' => 'paste your video id you want to embed',
'class' => 'youtube-widget'
]
);
}
public function form($instance)
{
$default = [
'title' => __(''),
'code' => __('')
];
$instance = wp_parse_args((array)$instance,$default);
echo "\r\n";
echo '<p>';
echo '<label for="'.$this->get_field_id('title').'">'.__('Title').':</label>';
echo '<input type="text" class="widefat" id="'.$this->get_field_id('title').'" value="'.esc_attr($instance['title']).'">';
echo '</p>';
echo '<p>';
echo '<label for="'.$this->get_field_id('code').'">'.__('Code').':</label>';
echo '<input type="text" class="widefat" id="'.$this->get_field_id('code').'" value="'.esc_attr($instance['code']).'">';
echo '</p>';
}
public function update($new_instance, $old_instance)
{
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
$instance['code'] = $new_instance['code'];
return $instance;
}
public function widget($args, $instance)
{
extract($args,EXTR_SKIP);
echo $before_widget;
echo '<iframe width="560" height="315" src="https://www.youtube.com/embed/';
echo $instance['code'];
echo '" frameborder="0" allowfullscreen></iframe>';
echo $after_widget;
}
}
The video player is displaying correctly. But after giving the video id in widget the video is not playing. It says,
An error occurred. Please try again later.