Create your first WordPress plugin

Well you are a WordPress developer but never create any WordPress plugin before. Ok great !! . This is the perfect place for you. Lets start to create your very first WordPress plugin with me.

Step 1 : Plugin Comment

Plugin comment define the introduction of the plugin. This is exactly same comment system that we used to make a WordPress theme. When we upload and activate a plugin, it shows plugin name, author name, author website links there. These information comes from the plugin comment. Here is the plugin comment sample.


/*
Plugin Name: My First Plugin
Plugin URI: http://wpcooltricks.com
Description: This is my first plugin ever.
Version: 1.0
Author: Shakil Zaman
Author URI: http://shakilzaman.com
License: GPLv2 or later
Text Domain: myfirstplugin
*/

In this plugin we will make a simple custom post type and show those post data in our website by use a shortcode.

Step 2 : Create a Custom Post

Use this code for create a custom post type Person.  


// Custom Post Person
function create_person() { 
register_post_type( 'person', array( 
'labels' => array(  
'name' => __( 'Person' ),  
'singular_name' => __( 'Person' ),  
'add_new_item' => __( 'Add New Person', 'text_domain' ) ),  

'public' => true, 
'has_archive' => true,  
'supports' => array('title','editor') ) ); 
}
add_action( 'init', 'create_person' );

After adding this custom post you can activate your plugin and check the Person menu on the left side of your admin dashboard.

Add some demo data in your person post. That will show in the website later.

Step 3 : Create Shortcode

If you don’t know how to create a Shortcode then please check this tutorial.  Create a function show_person_table(). In between this function create a HTML table and use WP_Query() to get all data from Person custom post.

<?php
// Show Person Table Shortcode
function show_person_table(){

?>
<table class="table">
<tr>
<th>Person</th>
<th>Details</th>
</tr>
<?php $args = array( 'post_type'=>'person' );
$query = new WP_Query( $args );
if($query->have_posts()){
while ($query->have_posts()){$query->the_post(); } ?>
<tr>
<td><?php the_title(); ?></td>
<td><?php the_content(); ?></td>
</tr>
</table>
<?php
}
}
add_shortcode('person','show_person_table');
?>

By using this action hook add_shortcode()  we made a shortcode [person] . If we add this shortcode to any WordPress pages or posts. It will show the output that comes from  show_person_table() function.

This is all our first WordPress plugin. Thanks for reading this tutorial. Hope it helps to start your Plugin journey.

Leave a Reply

Your email address will not be published. Required fields are marked *