Creating WordPress Short Code

If you need to create a short code for WordPress, you shouldn’t be reluctant. The following short code handling could be created as a plugin, but, this handling will be installed as if it were intended to be part of a theme. As a result, instead of being added as a plugin, it should be inserted in the functions.php in the theme directory. Remember, a functions.php file in the themes directory will be available just as if you had added it to the functions.php file in WordPress, but, your changes will not be lost with an upgrade of WordPress.

Creating a WordPress short code is easy. The following is an example of creating short code.

This short code creates a button for WP e-commerce to allow the visitor to click the button to order a product and immediately be dropped at the checkout page. This cuts a step out of the ordering process of a simple item in WP e-commerce.


/**
 * Custom shortcode function added to create a button that adds
 * a product to cart and takes customer directly to checkout page.
 *
 * Usage:
 *   [add_and_go_to_checkout class='my_button_class' 
 *       id=1 name='buy_my_product' value='Buy My Product' 
 *       image='image.jpg']
 *
 */
function wpsc_add_and_go_to_checkout_shortcode($atts) {
    // build form for button
    $shopping_cart_url = get_option('shpping_cart_url') ;
    $output = <<<GOTOCHECKOUTSELECTION
      <form class='go_direct' action='{$shopping_cart_url}' 
	     method='post'>
        <input  type='hidden' name='wpsc_ajax_action' 
	     value='add_to_cart'>
        <input  type='hidden' name='product_id' 
	     value='{$atts["id"]}'>
        <button type='submit' id='product__submit_button' 
	     class='{$atts["class"]}' name='{$atts["name"]}' 
         value='{$atts["value"]}'>
        <img src='{$atts["image"]}' alt='submit'></button>\\n">
      </form>
GOTOCHECKOUTSELECTION;
    return $output ;
}
add_shortcode( $tag = 'add_and_go_to_checkout', 
               $func = 'wpsc_add_and_go_to_checkout_shortcode') ;

Therefore, by using “add_shortcode,” creating a simple function, and add the function and add_shortcode command to the functions.php file in your theme directory, you can create a helper short code that meets the needs of your WordPress site.

Leave a Reply