How to create plugin in wordpress?

Hello welcome back guys, hope you have read my previous document on What is plugin?, so from now you have idea about why you need plugin in wordpress site.

In some cases, you have to write a plugin that’s the better practice than adding code to your functions.php file. And creating a plugin is far simpler than you might think.
In this post, I’ll show you how to create a plugin, and identify when it’s better to write a plugin instead of adding code to your theme.

When Should You Write a Plugin?

  • Sometimes when writing a plugin is best, and times when you can just add the code to your theme’s functions file.
  • Use functions.php when you need to add simple functionality related to the way your content is displayed (i.e. it won’t work without your theme activated). This might include adding extra fonts, for example.
  • Write a plugin for more complex functionality isn’t dependent on the theme. An example is registering post types – you don’t want to lose your post types if you change themes in the future at that time you can take help of plugin.

Create plugin

Let’s begin with creating simple plugin so you will have an idea about how can create plugin in wordpress. 🙂

To create a plugin, you simply create a file in your wp-content/plugins_name directory with the following opening code:

<?php
/**
 * Plugin Name: Ecodeblog test
 * Plugin URI: https://ecodeblog.com/
 * Description: Plugin description that you wnat to display on plugin page.
 * Version: 1.0
 * Author: Niket Joshi
 */
?>

You’ll need to edit the code above with your own details, but you can see it’s very simple.
Once you’ve saved your plugin, it will appear in the Plugins admin screen where you can activate it.

Writing Functions in Your Plugin

The most basic thing you can do in a plugin is write a function. You can then output that function using a hook or by typing the function name into your theme.

So let’s say you want to create a function for a Drop mail, and then add it in multiple places in your theme.

The function for your button would look something like this:

<?php 
function ecode_footer() { ?>
  <div class="cta">
    <p>Call us on 000-0000 or email <a href="mailto:sales@example.com">sales@example.com</a></p>
  </div>

<?php }

Now when you want to add your call to action button to your site, you just add the function in the relevant places in your theme template files, like so:

<?php ecode_footer(); ?>

This is much more efficient than adding that code to your theme every time you want a Drop a mail button – there’s less code for WordPress to run and less for you to maintain.

37
1
Share

You may also like...

2 Responses

  1. Sunil Dora says:

    Very useful post…

Leave a Reply

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