How I did it – WordPress plugin – “Did you know?”

This will take you through my code for creating a custom plugin in WordPress. This plugin uses a custom post type, a widget, and some CSS. Find the final product at the end of the post!

One of my clients was looking for a way to do quick, random promotions on his WordPress site. He wanted visitors to see his latest post, or tell them about a product they might not know he sells. So, I rolled up my sleeves and decided to create a simple but custom WordPress plugin.

  • Plugin name: Did you know?
  • Description: Quickly display random facts on your site and point your visitors to posts, affiliate links, or products.
  • Download: Did You Know? WordPress Plugin

So, this plugin needed to do a few things:

  1. Create a custom post type called “Did you know?”, where the user can quickly create a new “Fact”.
  2. Create a widget that displays a random fact every time the page refreshes
  3. Add some CSS styling that can be altered if the user desires

Step 1: Create a Custom Post Type

You could code everything up yourself for your custom post type, but why when you can just generate it? I used the WordPress Custom Post Type Generator to create the following:

/*-------------------------------------------------------------------------------------------*/
/* bt_did_you_know Post Type */
/*-------------------------------------------------------------------------------------------*/
class bt_did_you_know {

	function bt_did_you_know() {
		add_action('init',array($this,'create_post_type'));
	}

	function create_post_type() {
		$labels = array(
		    'name' => 'Facts',
		    'singular_name' => 'Fact',
		    'add_new' => 'Add New Fact',
		    'all_items' => 'All Facts',
		    'add_new_item' => 'Add New Fact',
		    'edit_item' => 'Edit Fact',
		    'new_item' => 'New Fact',
		    'view_item' => 'View Fact',
		    'search_items' => 'Search Facts',
		    'not_found' =>  'No Facts Found',
		    'not_found_in_trash' => 'No Facts found in trash',
		    'parent_item_colon' => 'Parent Fact:',
		    'menu_name' => 'Did you know?'
		);
		$args = array(
			'labels' => $labels,
			'description' => "A list of small facts linked to posts, products, or just for static informative text.",
			'public' => true,
			'exclude_from_search' => true,
			'publicly_queryable' => true,
			'show_ui' => true,
			'show_in_nav_menus' => true,
			'show_in_menu' => true,
			'show_in_admin_bar' => true,
			'menu_position' => 20,
			'menu_icon' => null,
			'capability_type' => 'post',
			'hierarchical' => false,
			'supports' => array('title','editor'),
			'has_archive' => false,
			'rewrite' => array('slug' => 'fact'),
			'query_var' => true,
			'can_export' => true
		);
		register_post_type('bt_did_you_know',$args);
	}
}

$bt_did_you_know = new bt_did_you_know();

Step 2: Create a widget

Creating the widget was just a tiny bit more complex. Obviously the best place to look for updated documentation on this process is the WordPress Codex. Here’s my widget. Notice at line 18-19 I’ve commented out the ability to use WordPress’ default “title” attribute of the widget. I realize this is not best practice, but I since I knew my client didn’t actually want to customize this at all, I disabled the title by commenting it out, and just put the title in the body of the widget, to be styled with css.

/*-------------------------------------------------------------------------------------------*/
/* "Did you know?" widget */
/*-------------------------------------------------------------------------------------------*/

class bt_random_fact_widget extends WP_Widget {

	function bt_random_fact_widget() {
		// Instantiate the parent object
		parent::__construct( false, 'Did you know? - Random Fact' );
	}

	function widget( $args, $instance ) {
		// Widget output
		extract( $args );
		$title = apply_filters( 'widget_title', $instance['title'] );

		echo $before_widget;
	//	if ( ! empty( $title ) )
	//		echo $before_title . $title . $after_title;
		$args = array(
					  'post_type' => 'bt_did_you_know',
					  'posts_per_page' => 1,
					  'orderby' => 'rand'
					  );
		$loop = new WP_Query( $args );
		while ( $loop->have_posts() ) : $loop->the_post();
			echo '</pre>
<div class="did-you-know-title">» ' . $title . '</div>
<pre>';
			echo '</pre>
<div class="did-you-know">';
 the_content();
 echo '</div>
<pre>';
		endwhile;
		echo $after_widget;
	}

	function update( $new_instance, $old_instance ) {
		// Save widget options
		$instance = array();
		$instance['title'] = strip_tags( $new_instance['title'] );

		return $instance;
	}

	 function form( $instance ) {
		// Output admin widget options form
		if ( isset( $instance[ 'title' ] ) ) {
			$title = $instance[ 'title' ];
		} else {
			$title = __( 'Did you know?', 'text_domain' );
		}
		?>

<label for="<?php echo $this->get_field_id( 'title' ); ?>"><!--?php _e( 'Title:' ); ?--></label>
            <input id="<?php echo $this->get_field_id( 'title' ); ?>" class="widefat" type="text" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo esc_attr( $title ); ?>" />

        <!--?php <br ?-->	}
}

add_action( 'widgets_init', 'myplugin_register_widgets' );
function myplugin_register_widgets() {
	register_widget( 'bt_random_fact_widget' );
}

Step 3: Apply CSS to the Widget

The final step was to apply the CSS to the widget. But I only wanted to apply the CSS when the widget was activated. So I used WordPress’ is_active_widget function to queue up the stylesheet.

add_action( 'init', 'check_widget' );
function check_widget() {
    if( is_active_widget( false, false, 'bt_random_fact_widget', true ) ) {
		wp_register_style( 'enqueue_my_styles', plugins_url('didyouknow.css', __FILE__) );
        wp_enqueue_style( 'enqueue_my_styles' );
	}
}

Final Product

Download the final product (free of course!): Did You Know? WordPress Plugin

Installation Instructions:

  • Go to Plugins > Add New. Click Upload and upload the zip file to your WordPress site.
  • Activate the plugin and you’ll see a new post type appear on the left menu bar called Did You Know?
  • Add a few new facts (to test it out)
  • Go to Appearance > Widgets and drag the Did You Know? – Random Facts widget into your sidebar.
  • Go to your home page (or wherever your sidebar appears), and you should see a random fact display every time you refresh the page!

If you installed it, I’d love to hear thoughts, comments, feedback. As I mentioned above, this was a custom job for a client, so if you find use for it, great!

About bentedder

Ben Tedder is a front-end web developer. He loves WordPress, SharePoint, and Drupal, along with jQuery, CSS, and good 'ol HTML. +Ben Tedder on Google or follow @bentedder

Join the discussion!