Web Programming TutorialsLearn How to Create a Plugin in WordPress.

Learn How to Create a Plugin in WordPress.

wordpressplugins(1)-740X296

Hi y’all, today we are going to learn how to create a plugin and will use the Eduonix YouTube video as an example. In this example, we are fetching a course video from YouTube in your WordPress website. Three things you will learn from this blog is: How to create a video post type, how to create dynamic embed code for videos, and how to use the Settings API.

Basically we are going to create the following two things:

1) We are going to create a Disable plugin for full screen.1

2) We will build a custom post type plugin for YouTube videos.2

So let’s start with our installation!

First, we need XAMPP (if you already have WAMPP, then you don’t need XAMPP) and second, we need to set up WordPress. Follow the steps below for installation:

FOR XAMPP:

1) Download XAMPP from the link “https://www.apachefriends.org/index.htmlfor your operating system. Once you complete downloading, open it you will get the “XAMPP Control Panel”. Click on the start button for Apache and MySQL, it should be like this.3

2) Once you are done with this, go to your browser and type, “localhost/phpmyadmin”. You will get the following screen.
4

3) Click on “Database”. After clicking on it, you will get the database window. Create your database with name “mywordpress”.
5

FOR WORDPRESS:

1) Go to your XAMPP folder and you will see the “htdocs” folder in it. Open that folder and in that, folder create a new folder with the name “mywordpress”.

2) Visit “wordpress.org” website and download the latest version. After downloading open that folder and copy all the content and paste it in your “mywordpress” folder.

3) Open the “mywordpress” folder using one of the editors. Rename the “wp-config-sample.php” file with “wp-config”. After that set your database name, username,password.

By default, username will be “root”, if you don’t set the password and then make it blank.
6

4) After that, you have to generate a key for it, so go to your browser and search for the WordPress key generator. Click on the secret key generator, you will get the key format like this:
7

Copy this code and paste it here:
8

5) Once you are done with this, save it and go to the “localhost/mywordpress”. You will get the following window:
9

Select English and click on continue, you will get the following screen. Fill the information and click on “Install WordPress” button.
10

6) Once you are done with this, you will get the success page and it will ask for you to login. Put the username and password and click on login, you will get the following screen:
11

7) You will be able to see the “mywordpress”. Once you click on it, it shows the option of “Visit Site”. Click on the “visit site” button, you will get the ‘your wordpress’ website like this:
12

So, let’s start with actual coding:

1) Click on your “myswordpress” folder you will be able to see the wp-content In that, click on plugins folder. Create a new folder with name youtube-vid-gallery. In this folder, create the following structure of the folders as follows:
13

The “css” folder, create the “style.css” and “style-admin.css” files.
The “js” folder create the “main.js” file.
The “includes” folder will contain the following files:
14

2) This is the main plugin code. Add it in your “youtube-vid-gallery.php” In this code, we have included all the files that we have created in the includes folder.

<?php
/**
* Plugin Name: Youtube Vid Gallery
* Description: Add a Youtube video gallery to your website
* Version: 1.0
* Author: Shrutika
* Author URI: 
**/

// Exit If Accessed Directly
if(!defined('ABSPATH')){
    exit;
}

// Load Scripts
require_once(plugin_dir_path(__FILE__) . '/includes/youtube-vid-gallery-scripts.php');

// Load Shortcodes
require_once(plugin_dir_path(__FILE__) . '/includes/youtube-vid-gallery-shortcodes.php');

// Check if admin and include admin scripts
if ( is_admin() ) {
	// Load Custom Post Type
	require_once(plugin_dir_path(__FILE__) . '/includes/youtube-vid-gallery-cpt.php');

	// Load Settings
	require_once(plugin_dir_path(__FILE__) . '/includes/youtube-vid-gallery-settings.php');
	
	// Load Post Fields
	require_once(plugin_dir_path(__FILE__) . '/includes/youtube-vid-gallery-fields.php');
}

3) Now, the next step is to add the code in “youtube-vid-gallery-scripts.php”. In this code, we use the “wp_enqueue_style”. It enqueue a CSS stylesheet and Registers the style, if source provided (does NOT overwrite it) and enqueues.

Syntax:

wp_enqueue_style ( string $handle, string|bool $src = false, array $deps = array(), string|bool $ver = false, string $media = 'all' )

Description:

$handle
(string) (Required) Name of the stylesheet.
$src
(string|bool) (Optional) Path to the stylesheet from the root directory of WordPress. Example: ‘/css/mystyle.css’.
Default value: false
$deps
(array) (Optional) An array of registered style handles thi stylesheet depends on.

Default value: array()

$ver
(string|bool) (Optional) String specifying the stylesheet version number, if it has one. This parameter is used to ensure that the correct version is sent to the client regardless of caching, and so should be included if a version number is available and makes sense for the stylesheet.

Default value: false

The “wp_enqueue_script” is provided to Enqueue a script and Register the script if $src provided (does NOT overwrite), and enqueues it.

Syntax:

wp_enqueue_script ( string $handle, string|bool $src = false, array $deps = array(), string|bool $ver = false, bool $in_footer = false )

Description :

$handle
(string) (Required) Name of the script.
$src
(string|bool) (Optional) Path to the script from the root directory of WordPress. Example: ‘/js/myscript.js’.

Default value: false

$deps
(array) (Optional) An array of registered handles this script depends on.

Default value: array()

$ver
(string|bool) (Optional) String specifying the script version number, if it has one. This parameter is used to ensure that the correct version is sent to the client regardless of caching, and so should be included if a version number is available and makes sense for the script.

Default value: false

$in_footer
(bool) (Optional) Whether to enqueue the script before </head> or before </body>. Default ‘false’. Accepts ‘false’ or ‘true’.

Default value: false

Add your code in “youtube-vid-gallery-scripts.php”

<?php

// Check if admin and add admin scripts
if ( is_admin() ) {
	// Add Admin Scripts
	function yvg_add_admin_scripts(){
	    	wp_enqueue_style('yvg-main-admin-style', plugins_url() . '/youtube-vid-gallery/css/style-admin.css');
	    	wp_enqueue_script('yvg-main-script',plugins_url().'/youtube-vid-gallery/js/main.js', array('jquery'));
	}

	add_action('admin_init','yvg_add_admin_scripts');
}


// Add Scripts
function yvg_add_scripts(){
    wp_enqueue_style('yvg-main-style', plugins_url() . '/youtube-vid-gallery/css/style.css');
    wp_enqueue_script('yvg-main-script',plugins_url().'/youtube-vid-gallery/js/main.js', array('jquery'));
}

add_action('wp_enqueue_scripts','yvg_add_scripts');

WordPress Training for Beginners From Scratch

4) After that we will create a custom post type in the “youtube-vid-gallery-ctp.php” We are using two types of filters: singular and plural. Basically, apply_filters() interacts with the global $wp_filters array. It just checks the array if the current filter (or hook) has an action(/callback function) attached and then calls it.

For example:
A string that changes when the number of items changes. In English, you have “One comment” and “Two comments”. In other languages, you can have multiple plural forms. To handle this in WordPress you can use the _n() function.

printf(
    _n(
        '%s comment',
        '%s comments',
        get_comments_number(),
        'my-plugin'
    ),
    number_format_i18n( get_comments_number() )
);
_n() accepts 4 arguments:

singular – the singular form of the string (note that it can be used for numbers other than one in some languages, so ‘%s item’ should be used instead of ‘One item’)

plural – the plural form of the string

count – the number of objects, which will determine whether the singular or the plural form should be returned (there are languages, which have far more than 2 forms)

text domain – the plugins text domain

Add this code:

<?php

// Create Custom Post Type
function yvg_register_video(){
	$singular_name = apply_filters('yvg_label_single', 'Video');
	$plural_name = apply_filters('yvg_label_plural', 'Videos');

	$labels = array(
		'name' => $plural_name,
		'singular_name' => $singular_name,
		'add_new' 		=> 'Add New',
		'add_new_item'	=> 'Add New '.$singular_name,
		'edit'			=> 'Edit',
		'edit_item'		=> 'Edit '.$singular_name,
		'new_item'		=> 'New '.$singular_name,
		'view'			=> 'View',
		'view_item'		=> 'View '.$singular_name,
		'search_items'	=> 'Search '.$plural_name,
		'not_found'		=> 'No '.$plural_name.' Found',
		'not_found_in_trash'		=> 'No '.$plural_name.' Found',
		'menu_name'		=> $plural_name
	);

	$args = apply_filters('yvg_video_args', array(
		'labels'		=> $labels,
		'description'	=> 'Videos by category',
		'taxonomies'	=> array('category'),
		'public'		=> true,
		'show_in_menu'	=> true,
		'menu_position'	=> 5,
		'menu_icon'		=> 'dashicons-video-alt',
		'show_in_nav_menus'	=> true,
		'capability_type'	=> 'post',
		'supports'		=>	array(
			'title'
		)
	));

	// Register Post Type
	register_post_type('video', $args);
}

add_action('init', 'yvg_register_video');

5) After adding this code, run your website. Click on Plugins and you will get the following window. Just click on activate.
16

6) Next step, we will be creating a form for adding video information and saving it. Add the following code in your “youtube-vid-gallery-fields”:

<?php
function yvg_add_fields_metabox(){
add_meta_box(
'yvg_video_fields',
__('Video Fields'),
'yvg_video_fields_callback',
'video',
'normal',
'default'
);
}

 add_action('add_meta_boxes', 'yvg_add_fields_metabox');

 // Display meta Box Content
 function yvg_video_fields_callback($post){
 wp_nonce_field(basename(__FILE__), 'yvg_videos_nonce');
 $yvg_video_stored_meta = get_post_meta($post->ID);
 ?>
 <div class="wrap video-form">
 <div class="form-group">
<label for="video-id"><?php esc_html_e('Video ID', 'yvg-domain'); ?></label>
<input type="text" name="video_id" id="video-id" value="<?php if(!empty($yvg_video_stored_meta['video_id'])) echo esc_attr($yvg_video_stored_meta['video_id'][0]); ?>">
</div>
 <div class="form-group">
 <label for="details"><?php esc_html_e('Details', 'yvg-domain'); ?></label>
 <?php
 $content = get_post_meta($post->ID, 'details', true);
 $editor = 'details
 $settings = array(
'textarea_rows' => 5,
 'media_buttons' => false
);
wp_editor($content, $editor, $settings);
?>
 </div>
<?php if(isset($yvg_video_stored_meta['video_id'][0])) : ?>
 <iframe width="560" height="315" src="https://www.youtube.com/embed/<?php echo $yvg_video_stored_meta['video_id'][0]; ?>" frameborder="0" allowfullscreen></iframe>
 <?php endif; ?>
</div>
 <?php
 }

 function yvg_video_save($post_id){
 $is_autosave = wp_is_post_autosave($post_id);
 $is_revision = wp_is_post_revision($post_id);
 $is_valid_nonce = (isset($_POST['yvg_videos_nonce']) && wp_verify_nonce($_POST['yvg_videos_nonce'], basename(__FILE__))) ? 'true' : 'false';
  if($is_autosave || $is_revision || !$is_valid_nonce){
 return;
 }
if(isset($_POST['video_id'])){
 update_post_meta($post_id, 'video_id', sanitize_text_field($_POST['video_id']));
 }
if(isset($_POST['details'])){
update_post_meta($post_id, 'details', sanitize_text_field($_POST['details']));
 }
 }
add_action('save_post', 'yvg_video_save');

Once you are done with this, you will get the following screen:
17

7) Go to “Youtube” and search for “Eduonix”. After that open one video and copy the video id and add it in your video form.
18

After that, add the description and you will get a final window like this
19

Click on Publish button.

8) Add this css code in your “Style-admin.css” file.

Style-admin.css
.video-form{
	font-size:18px;
	padding-top:15px;
}

.video-form input{
	padding:5px;
}

.video-form label{
	display:block;
	padding-bottom:10px;
}

.video-form .form-group{
	padding-bottom:15px;
}

9) Add this code in your “youtube-vid-gallery-shortcodes.php” to list out the videos.

<?php

// List Videos
function yvg_list_videos($atts, $content = null){
	global $post;

	$atts = shortcode_atts(array(
		'title' => 'Video Gallery',
		'count' => 20,
		'category' => 'all'
	), $atts);

	// Check Category
	if($atts['category'] == 'all'){
		$terms = '';
	} else {
		$terms = array(
			array(
				'taxonomy' 	=> 'category',
				'field'		=> 'slug',
				'terms'		=> $atts['category']
		));
	}

	// Query Args
	$args = array(
		'post_type'			=> 'video',
		'post_status'		=> 'publish',
		'orderby'			=> 'created',
		'order'				=> 'DESC',
		'posts_per_page'	=> $atts['count'],
		'tax_query'			=> $terms
	);

	// Fetch Videos
	$videos = new WP_Query($args);

	// Check for Videos
	if($videos->have_posts()){
		$category = str_replace('-', ' ', $atts['category']);

		// Init Output
		$output = '';

		// Build Output
		$output .= '<div class="video-list">';

		while($videos->have_posts()){
			$videos->the_post();

			// Get Field values
			$video_id = get_post_meta($post->ID, 'video_id', true);
			$details = get_post_meta($post->ID, 'details', true);

			$output .= '<div class="yvg-video">';
			$output .= '<h4>'.get_the_title().'</h4>';
			if(get_settings('yvg_setting_disable_fullscreen')){
				$output .= '<iframe width="560" height="315" src="https://www.youtube.com/embed/'.$video_id.'" frameborder="0"></iframe>';
			} else {
				$output .= '<iframe width="560" height="315" src="https://www.youtube.com/embed/'.$video_id.'" frameborder="0" allowfullscreen></iframe>';
			}
			
			$output .= '<div>'.$details.'</div>';
			$output .= '</div><br></hr>';
		}


		$output .= '</div>';

		// Reset Post Data
		wp_reset_postdata();

		return $output;
	} else {
		return '<p>No Videos Found</p>';
	}
}

// Video List Shortcode
add_shortcode('videos', 'yvg_list_videos');

Following this, click on “Pages” and create a page called “Videos”.
20

Once you are done with this, click on “Appearance” and in that select “Menus”. You will get the following screen:
21

After that, check the “Videos” option and click on the “Add to Menu” button. Once the video gets added, you will get the following screen. It shows that the videos have been added in a menu structure. Click on the Save menu button to save the changes.
22

After that, click on “Manage Locations” tab. In that, select primary menu as “MENU” and save it .

Add the following code in your “style.css” file. In that we are giving a bottom to video.

.yvg-video{
margin-bottom:20px;
}

Once you have done this, you will get following output:
23

10) The last part is the coding for “Disable screen”. Go to your “youtube-vid-gallery-settings.php” and add this code there:

<?php

function yvg_settings_api_init(){
	add_settings_section(
		'yvg_setting_section',
		'YouTube Vid Gallery Settings',
		'yvg_setting_section_callback',
		'reading'
	);

	add_settings_field(
		'yvg_setting_disable_fullscreen',
		'Disable Fullscreen',
		'yvg_setting_disable_fullscreen_callback',
		'reading',
		'yvg_setting_section'
	);

	register_setting('reading', 'yvg_setting_disable_fullscreen');
}

add_action('admin_init', 'yvg_settings_api_init');

function yvg_setting_section_callback(){
	echo '<p>Settings for Youtube Vid Gallery</p>';
}

function yvg_setting_disable_fullscreen_callback(){
	echo '<input name="yvg_setting_disable_fullscreen" id="yvg_setting_disable_fullscreen" type="checkbox" value="1" class="code"' . checked(1, get_option('yvg_setting_disable_fullscreen'), false);
}

Once you have finished adding this code, you will get the “disable button” functionality in “Settings”-> “Reading” submenu. You will be able to see the following button:
24

If you check the disable button, you will get the error i.e “Fullscreen is unavaibale”, and if it is unchecked, you will be able to view the video in Fullscreen.
25

“In this section we learn a few things including how to create a custom post type for video, how to create video posts using the Youtube video id, as well as the video details field. We then learnt how to create the settings API, and how to set the video custom size. Finally, we also covered how to create a Fullscreen disable option.

I hope this has been helpful for you guys in understanding how to create a plugin in WordPress.

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Exclusive content

- Advertisement -

Latest article

21,501FansLike
4,106FollowersFollow
106,000SubscribersSubscribe

More article

- Advertisement -