Site icon Anthony Carbon

How to start creating a simple WordPress plugin?

Step 1

Think about the name of your plugin.

Step 2

Example is Shortcode URL plugin. Create a shortcode-url folder name inside of  wp-content/plugins/.

Step 3

Create shortcode-url.php file inside wp-content/plugins/ folder and put the codes below inside of your shortcode-url.php file.

<?php

/**
 * Plugin Name: Shortcode URL
 * Plugin URI: https://www.anthonycarbon.com/
 * Description: Shortcode URL is built for you.
 * Author: <a href="https://www.anthonycarbon.com/">Anthony Carbon</a>
 * Text Domain: shortcode-url
 * Version: 1.0.0
 **/

if ( ! defined( 'ABSPATH' ) ){ exit; }

Step 4

Create ReadMe.txt file inside of your shortcode-url folder.

Step 5

Add this code below “if ( ! defined( ‘ABSPATH’ ) ){ exit; }”.

add_shortcode( 'shortcode-url', 'shortcode_url' );
function shortcode_url() {
    return get_bloginfo( 'url' );
}

Step 6

Install your plugin now and this can be use in your development task.

Example usage

<img src="[shortcode-url]/wp-content/uploads/2017/06/4nthony.png" alt="" />

Step 7

Using shortcode attributes, we will make the “[shortcode-url]” more useful.

add_shortcode( 'shortcode-url', 'shortcode_url' );
function shortcode_url( $atts ) {
    $a = shortcode_atts( array(
        'type' => '', // post / page / category
        'base' => '', // content / uploads
        'id' => '', // post, page, category ID
    ), $atts );
    if( $a['type'] && empty( $a['base'] ) ) :
		switch( $a['type'] ){
			case 'post':
				return get_permalink( $a['id'] );
				break;
			case 'page':
				return get_permalink( $a['id'] );
				break;
			case 'category':
				return get_category_link( $a['id'] );
				break;
		}
	endif;
    if( $a['base'] && empty( $a['type'] ) ) :
		switch( $a['base'] ){
			case 'content':
				return get_bloginfo( 'url' ) . '/wp-content/';
				break;
			case 'uploads':
				return get_bloginfo( 'url' ) . '/wp-content/uploads/';
				break;
		}
	endif;
    return get_bloginfo( 'url' );
}

Example usage

// 1578 is post ID of https://www.anthonycarbon.com/how-to-start-creating-a-simple-wordpress-plugin/
<a href="[shortcode-url type='post' id='1578']">How to start creating a simple WordPress plugin?</a>

// 4 is page ID of https://www.anthonycarbon.com/about-me/
<a href="[shortcode-url type='page' id='4']">About Me</a>

// 2 is category ID of https://www.anthonycarbon.com/category/blog/
<a href="[shortcode-url type='category' id='4']">Blog</a>

// output is https://www.anthonycarbon.com/wp-content
<img src="[shortcode-url base='content']/uploads/2017/06/4nthony.png" alt="" />

// output is https://www.anthonycarbon.com/wp-content/uploads
<img src="[shortcode-url base='uploads']/2017/06/4nthony.png" alt="" />
Exit mobile version