All Articles Kinsa Creative

Using WordPress Shortcodes to Place Specific Content on a Page

The Function

Add to the WordPress theme's functions.php file:

function my_shortcode_code( $atts ){
    $sh_attr = shortcode_atts( array( 'my_kwarg' => ''), $atts );
    if ( $sh_attr['my_kwarg'] != '' ) {
        // do something with the kwawrg value
        $my_var = 'something';
        return $my_var;
    }
    return '';
}

// add the shortcode
function register_my_shortcode() {
    add_shortcode( 'my_shortcode', 'my_shortcode_code' ); // the 2nd arg is the function, the first is a name for it
}

// register the shortcode
add_action( 'init', 'register_my_shortcode' );

In a post, reference the name of the shortcode set in the add_shortcode() call:

[my_shortcode  my_kwarg=something]

Alternately to referencing the shortcode in a post, the shortcode can be referenced in a template:

<?php echo do_shortcode( 'my_shortcode' ); ?>

Feedback?

Email us at enquiries@kinsa.cc.