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.
How to use? How to use?
- Create a new page and add shortcode.
- Open the page. It’ll show the output of the shortcode like below:
Code Snippet Code Snippet
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; |