Create a Simple Shortcode

Advertisement

Use code snippet to create a simple WordPress shortcode. I have created a sample shortcode prefix-portfolio with 2 attributes.

Before use change: Before use change:

  • Change the Prefix with your own unique prefix.
  • Change the prefix with your own unique prefix.

Top ↑

How to use? How to use?

  1. Create a new page and add shortcode.Create a Simple Shortcode 1
  2. Open the page. It’ll show the output of the shortcode like below:Create a Simple Shortcode 2

Top ↑

Code Snippet Code Snippet


<?php
/**
* Prefix Shortcode
*
* @todo Change the `Prefix` with your own unique prefix.
* @todo Change the `prefix` with your own unique prefix.
*
* @package Prefix
* @since 1.0.0
*/
if ( ! class_exists( 'Prefix_Shortcode' ) ) :
/**
* Prefix_Shortcode
*
* @since 1.0.0
*/
class Prefix_Shortcode {
/**
* Instance
*
* @access private
* @var object Class Instance.
* @since 1.0.0
*/
private static $instance;
/**
* Initiator
*
* @since 1.0.0
* @return object initialized object of class.
*/
public static function get_instance() {
if ( ! isset( self::$instance ) ) {
self::$instance = new self;
}
return self::$instance;
}
/**
* Constructor
*
* @since 1.0.0
*/
public function __construct()
{
// Register shortcode.
add_shortcode( 'prefix-portfolio', array( $this, 'shortcode_markup' ) );
}
/**
* Shortcode
*
* @since 1.0.0
* @param array $data Shortcode attributes.
* @return mixed Shortcode markup.
*/
function shortcode_markup( $data = array() )
{
$data = shortcode_atts(
array(
'attribute-1' => '',
'attribute-2' => '',
), $data
);
ob_start();
?>
<div class="prefix-shortcode">
<?php echo esc_html( $data['attribute-1'] ); ?>
<?php echo esc_html( $data['attribute-2'] ); ?>
</div>
<?php
return ob_get_clean();
}
}
/**
* Kicking this off by calling 'get_instance()' method
*/
Prefix_Shortcode::get_instance();
endif;

Leave a Reply