how to create shortcode in wordpress

posted in: Blog, wordpress plugin | 0

Usage

<?php add_shortcode( $tag , $func ); ?>

Parameters

$tag
(string) (required) Shortcode tag to be searched in post content

Default: None
$func
(callable) (required) Hook to run when shortcode is found

Default: None

Return Values

(none)

Examples

Simplest example of a shortcode tag using the API: [footag foo=”bar”]

function footag_func( $atts ) {
	return "foo = {$atts['foo']}";
}
add_shortcode( 'footag', 'footag_func' );

Example with nice attribute defaults: [bartag foo=”bar”]

function bartag_func( $atts ) {
	$atts = shortcode_atts( array(
		'foo' => 'no foo',
		'baz' => 'default baz'
	), $atts, 'bartag' );

	return "foo = {$atts['foo']}";
}
add_shortcode( 'bartag', 'bartag_func' );

Example with enclosed content: [baztag]content[/baztag]

function baztag_func( $atts, $content = "" ) {
	return "content = $content";
}
add_shortcode( 'baztag', 'baztag_func' );

If your plugin is designed as a class write as follows:

class MyPlugin {
	public static function baztag_func( $atts, $content = "" ) {
		return "content = $content";
	}
 }
 add_shortcode( 'baztag', array( 'MyPlugin', 'baztag_func' ) );

 

Leave a Reply