Developer's Roundtable Notes

Session: Create Your Own Shortcodes and Widgets

Shortcodes, Shortcodes

Shortcodes are very handy. And easy.

They let you place specific content into your posts and pages with just a simple command.

They are most commonly used for forms and sliders. Things you want to create once and then have the freedom to place in your content.

They look like this:

[ gallery ]

or, like this:

[ form id="1" ]

 

Why do you sometimes hear negative comments about shortcodes?

Because they contain actual content for your site. If they’re created in a theme, when you change themes (and you know you will), that content is gone.

That’s why we’ll be creating them in a plugin.

Problem solved.

 

Uses for Shortcodes

I use shortcodes to make life easier for my clients.

Some Examples:

Format a company name to always look the same, no matter where it is or who types it in. ( My ComPany® )

Add PayPal buttons in multiple places for different items – without having to create a new button and embed the code.

Add a consistently formatted button inside the content in a page or post.

Shortcode Example #1

For text that you want to be consistent throughout a site, such as a properly formatted company name:

<?php

function company_name() {
    return 'My ComPany&reg;' ;
}
add_shortcode( 'mycompany', 'company_name' );

?>

 
To use this, you simply type [mycompany] into your page, and it prints the company name formatted the way you want.

And the output is: My ComPany®

Shortcode Example #2

Add a button anywhere on your site and have it styled consistent with the rest of your buttons.

<?php

function button_shortcode( $atts ) {

extract( shortcode_atts( 
	array( 
		'text' => 'Submit', // the defaults
		'link' => '#'
		), 
		$atts 
	));

return '<a class="button" href="'. $link .'">' . $text . '</a>';
}

add_shortcode( 'mybutton', 'button_shortcode' );

?>

 To use this shortcode, add [mybutton text=”Go” link=”http://mydomain.com”] to your page or post.

Shortcode Example #3

Allow your client to add PayPal buttons without having to create the button and copy the code every time.

<?php

function paypal_shortcode( $atts ) {

$atts = ( shortcode_atts( 
    array( 
	'amount' => '50', 
	'name' => 'Payment to MyCompany' 
	), 
	$atts );
    $amount = absint ( $atts['amount'] ) ;
    $name = $atts['name'];

return '<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
                <div class="paypal">
                    <input type="hidden" name="cmd" value="_xclick">
                    <input type="hidden" name="business" value="email@mydomain.com">
                    <input type="hidden" name="amount" value="' . $amount. '">
					<input type="hidden" name="item_name" value="'.$name.'">
                    <input type="hidden" name="rm" value="0">
                    <input type="hidden" name="currency_code" value="USD">
                    <input type="image" src="https://www.paypal.com/en_US/i/btn/btn_buynow_sm.gif" name="submit" alt="PayPal - The safer, easier way to pay online">
                    <img alt="" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">
                </div>
            </form>';
}

add_shortcode( 'paypal_button', 'paypal_shortcode' );

?>

 To add a PayPal button, just type [ paypal_button amount=”10″ name=”My Item” ] into your page.

Enclosing Shortcode

An easy way to allow clients to use CSS-defined styles or colors in their content.

<?php

function blue_shortcode( $atts, $content = null ) {
	return '<span class="blue">' . $content . '</span>';
}

add_shortcode( 'blue', 'blue_shortcode' );

?>

This assumes, of course, that you have the .blue class in your stylesheet.
In the editor, you would type:  [blue]This is my text.[/blue]

Shortcodes Plugin

We’ve written some functions, now let’s protect them from disappearing.

Simply place them all into a site specific plugin.

<?php
/**
 * Plugin Name: Shortcodes for this site
 * Description: shortcodes for link button, company name, blue text, and PayPal button.
 * Version: 1.0
 * Author: Diana Nichols
 * Author URI: http://www.lavenderthreads.com
 */

/* company name ************************/
function company_name() {
    return 'My ComPany&reg;' ;
}
add_shortcode( 'mycompany', 'company_name' );


/* button ************************/
function button_shortcode( $atts ) {
    $atts = shortcode_atts( 
    array( 
        'text' => 'Submit'
        'link' => '#';
        ), 
        $atts );
    $text = $atts['text'];
    $link = $atts['link'];

    return '<a class="button" href="' .$link. '>' . $text . '</a>';
}
add_shortcode( 'mybutton', 'button_shortcode' );


/* paypal ************************/
function paypal_shortcode( $atts ) {

$atts = ( shortcode_atts( 
    array( 
	'amount' => '50', 
	'item' => 'Payment to MyCompany' 
	), 
	$atts );
    $amount = absint( $atts['amount'] );
    $item = $atts['item'];
 
return '<form action="https://www.paypal.com/cgi-bin/webscr" method="post">
                <div class="paypal-donations">
                    <input type="hidden" name="cmd" value="_xclick">
                    <input type="hidden" name="business" value="email@mydomain.com">
                    <input type="hidden" name="amount" value="' . $amount. '">
					<input type="hidden" name="item_name" value="'.$item.'">
                    <input type="hidden" name="rm" value="0">
                    <input type="hidden" name="currency_code" value="USD">
                    <input type="image" src="https://www.paypal.com/en_US/i/btn/btn_buynow_sm.gif" name="submit" alt="PayPal - The safer, easier way to pay online">
                    <img alt="" src="https://www.paypal.com/en_US/i/scr/pixel.gif" width="1" height="1">
                </div>
            </form>';
}
add_shortcode( 'paypal_button', 'paypal_shortcode' );

/* blue ****************************/
function blue_shortcode( $atts, $content = null ) {
    return '<span class="blue">' . $content . '</span>';
}
add_shortcode( 'blue', 'blue_shortcode' );

?>

 

Shortcode Reminders

How to remind yourself, and clients, how to use the shortcodes:

Add this function to the bottom of the plugin.

<?php

function my_admin_notice() {
    $screen = get_current_screen();
    if ( $screen->base === 'post' ) { // only appears on "post" pages (including post-edit)

    ?>
    <div class="update-nag">
        <p><?php _e( '[company] will insert your company name', 'lavender' ); ?><br>
        <?php _e( '[paypal amount="xx" item="item name"] will insert a PayPal button', 'lavender' ); ?><br>
        <?php _e( '[mybutton text="button text" link="http://site.com"] will insert a link button', 'lavender' ); ?></p>
    </div>
<?php
	}
}
add_action( 'admin_notices', 'my_admin_notice' );

?>

This will add a note at the top of all add and edit pages for posts and pages.

Admittedly, this is not the most elegant solution, but it is much easier than adding custom buttons to the TinyMCE editor.

 

DIY Widgets

Examples:

A meetup notice
A special announcement
A testimonial
A welcome message for your users
Anything you want to easily put into a sidebar or widget area

Very Simple (Silly) Widget

<?php

/*
Plugin Name: Silly Widget Plugin
Description: A simple plugin that adds a simple widget
Version: 1.0
Author: Diana Nichols
Author URI: http://www.lavenderthreads.com/
License: GPL2
*/

class Silly_Widget extends WP_Widget {

	// 1. Register the Widget
	function __construct() {
		parent::__construct(
			'silly_widget', 
			__( 'Silly Widget', 'text_domain' ), 
			array( 'description' => __( 'Print some silly text', 'text_domain' ), ) 
		);
	}

	// 2. Front End Display
	public function widget( $args, $instance ) {
		echo $args['before_widget']; // because some themes use before_widget and after_widget hooks
				
		// this is the action of the widget
		echo __( '<p><strong>If people never did silly things nothing intelligent would ever get done.</strong></p><p style="text-align:right"><em>~ Ludwig Wittgenstein</em><p>', 'text_domain' );
		// 
		
		echo $args['after_widget'];
	}

	// 3. Widget Admin
	public function form( $instance ) {
		echo __('This widget has no options', 'text-domain'); 
	}

} // end of the class


// register Silly_Widget widget
function register_silly_widget() {
    register_widget( 'Silly_Widget' );
}
add_action( 'widgets_init', 'register_silly_widget' );

?>

 

Widget with a Custom Title

<?php

/*
Plugin Name: My Title Widget Plugin
Description: A simple plugin that adds a simple widget
Version: 1.0
Author: Diana Nichols
Author URI: http://www.lavenderthreads.com/
License: GPL2
*/

class My_Title_Widget extends WP_Widget {

	// 1. Register the Widget
	function __construct() {
		parent::__construct(
			'my_title_widget', 
			__( 'My Title Widget', 'text_domain' ), 
			array( 'description' => __( 'Prints Hello World', 'text_domain' ), ) 
		);
	}

	// 2. Front End Display
	public function widget( $args, $instance ) {
		echo $args['before_widget']; // because some themes use before_widget and after_widget hooks
		if ( ! empty( $instance['title'] ) ) {
			echo $args['before_title'] . apply_filters( 'widget_title', $instance['title'] ). $args['after_title'];
		}
		
		// this is the action of the widget
		echo __( 'Hello, World!', 'text_domain' );
		// 
		
		echo $args['after_widget'];
	}

	// 3. Widget Admin
	public function form( $instance ) {
		$title = ! empty( $instance['title'] ) ? $instance['title'] : __( 'New title', 'text_domain' );
		?>
		<p>
		<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label> 
		<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo esc_attr( $title ); ?>">
		</p>
		<?php 
	}

	// 4. Update / Save the widget in the database
	public function update( $new_instance, $old_instance ) {
		$instance = array();
		$instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : '';

		return $instance;
	}

} // end of the class


// register My_Widget widget
function register_my_title_widget() {
    register_widget( 'My_Title_Widget' );
}
add_action( 'widgets_init', 'register_my_title_widget' );
?>

 

Testimonial Widget

<?php
/*
Plugin Name: Testimonial Widget Plugin
Description: A simple plugin that adds a simple widget
Version: 1.0
Author: Diana Nichols
Author URI: http://www.lavenderthreads.com/
License: GPL2
*/

class dn_testimonial_widget extends WP_Widget {

	function __construct() {
		parent::__construct(
		'dn_testimonial_widget', 		
		'Testimonial Widget', // Widget name  - will appear in UI		
		array( 'description' => __('Include a testimonial in your sidebar', 'lavender') ) // Widget description
		);
	}

	// Displaying widget front-end
	public function widget( $args, $instance ) {
		$name = $instance['name'];
		$testimonial = $instance['testimonial'];

		// before and after widget arguments  -  defined by themes
		echo $args['before_widget'];

		echo '<div class="widget-text wp_widget_plugin_box">';
		   if( $testimonial ) {
				echo '<p style="font-weight:bold;margin-bottom:0;">"'.$testimonial.'"</p>';
			}
			if( $name ) {
				echo '<p style="text-align:right;font-size:.9em;"><em>'.$name.'</em></p>';
		   }
		echo '</div>';

		echo $args['after_widget'];
		}
		
	// Widget admin 
	public function form( $instance ) {
		if ( isset( $instance[ 'name' ] ) ) {
			$name = esc_attr($instance[ 'name' ]);
			$testimonial = esc_textarea($instance['testimonial']);
		} else {
			$name = '';
			$testimonial = '';
		}
	?>
	<p>
		<label for="<?php echo $this->get_field_id('name'); ?>">Name:</label>
		<input class="widefat" id="<?php echo $this->get_field_id('name'); ?>" name="<?php echo $this->get_field_name('name'); ?>" type="text" value="<?php echo $name; ?>" />
		</p>
		<p>
		<label for="<?php echo $this->get_field_id('testimonial'); ?>">Testimonial:</label>
		<textarea class="widefat" id="<?php echo $this->get_field_id('testimonial'); ?>" name="<?php echo $this->get_field_name('testimonial'); ?>"><?php echo $testimonial; ?></textarea>
	</p>
	<?php 
	}
	
	// Updating widget 
	public function update( $new_instance, $old_instance ) {
		$instance = array();
		$instance['name'] = ( ! empty( $new_instance['name'] ) ) ? strip_tags( $new_instance['name'] ) : '';
		$instance['testimonial'] = ( ! empty( $new_instance['testimonial'] ) ) ? strip_tags( $new_instance['testimonial'] ) : '';
		return $instance;
	}
	
} // end of Class

// Register and load the widget
function dn_load_widget() {
	register_widget( 'dn_testimonial_widget' );
}
add_action( 'widgets_init', 'dn_load_widget' );

?>

 

Display a Widget Anywhere

Did you know? You can display a widget anywhere in a template:

<?php the_widget( $widget, $instance, $args ); ?> 

 http://codex.wordpress.org/Function_Reference/the_widget

Skip to toolbar