WordPress shortcode

Shortcodes are the codes inserted in post or page content which will be replaced with other content on post or page view. Do not use hyphens (-) in shortcode names, use an underscore (_) instead of it. Bad: [short-code]; good: [short_code].
Example:

[pagelist]

Example with parameters:

[pagelist depth="3" child_of="4"]

Example with content:

[header]title[/header]

PHP code for "[pagelist]" shortcode:

<?php
function pagelist_shortcode( $atts ) {
	$input_atts = shortcode_atts( array(
		'depth' => '0',
		'child_of' => '0'
	), $atts );
 
	$page_list_args = array(
		'depth' => $input_atts['depth'],
		'child_of' => $input_atts['child_of']
	);
	$wp_list_pages = wp_list_pages( $page_list_args );
 
	if ($wp_list_pages) {
		return '<ul>'.$wp_list_pages.'</ul>';
	} else {
		return '';
	}
}
add_shortcode( 'pagelist', 'pagelist_shortcode' );
?>

PHP code for "[header]" shortcode:

<?php
function header_shortcode( $atts, $content = null ) {
	$content = force_balance_tags($content);
	$content = do_shortcode( $content );
	return '<h2>'.$content.'</h2>';
}
add_shortcode( 'header', 'header_shortcode' );
?>

Leave a Reply

Your email address will not be published. Required fields are marked *