add_shortcode()

最后更新于:2021-11-25 19:41:11

add_shortcode( string$tag, callable$callback)

Adds a new shortcode.

参数

$tag

(string) (Required) Shortcode tag to be searched in post content.

$callback

(callable) (Required) The callback function to run when the shortcode is found. Every shortcode callback is passed three parameters by default, including an array of attributes ($atts), the shortcode content or null if not set ($content), and finally the shortcode tag itself ($shortcode_tag), in that order.

源文件

文件: gc-includes/shortcodes.php

function add_shortcode( $tag, $callback ) {
	global $shortcode_tags;

	if ( '' === trim( $tag ) ) {
		_doing_it_wrong(
			__FUNCTION__,
			__( 'Invalid shortcode name: Empty name given.' ),
			'4.4.0'
		);
		return;
	}

	if ( 0 !== preg_match( '@[<>&/[]x00-x20=]@', $tag ) ) {
		_doing_it_wrong(
			__FUNCTION__,
			sprintf(
				/* translators: 1: Shortcode name, 2: Space-separated list of reserved characters. */
				__( 'Invalid shortcode name: %1$s. Do not use spaces or reserved characters: %2$s' ),
				$tag,
				'& / < > [ ] ='
			),
			'4.4.0'
		);
		return;
	}

	$shortcode_tags[ $tag ] = $callback;
}
function gcdocs_the_shortcode_func( $atts ) {
	$attributes = shortcode_atts( array(
		'title' => false,
		'limit' => 4,
	), $atts );
	
	ob_start();

	// include template with the arguments (The $args parameter was added in v5.5.0)
	get_template_part( 'template-parts/gcdocs-the-shortcode-template', null, $attributes );

	return ob_get_clean();

}
add_shortcode( 'gcdocs_the_shortcode', 'gcdocs_the_shortcode_func' );