Advertisement
Plugins

Random Quote Plugin With Custom Post Type

by

This is the second part of creating a random quote plugin, but this time with custom post types.


In this second version of the random quote plugin we move a bit further and use some more tools and functions. Custom post types are available since WordPress v3.0. They allow developers to add different types of content to their plug-ins and themes and with that you can easily extend WordPress' CMS functionality.

You can find the first version of the plugin here. If you are just starting out with plugin development or want a quick refresh it is recommended to read that first.


1. Basic Data

This is the data needed for every plugin. Simple things like author, plugin name, description and so on.

<?php
/*
Plugin Name: Adam's Random Quote
Version: 2.0
Plugin URI: http://wp.tutsplus.com
Description: Loads a Random Quote from custom post types
Author: Adam Burucs
Author URI: http://wp.tutsplus.com
*/
?>

2. Register Custom Post Type

Custom post types in WordPress

Before we can use the random quote custom post type we have to set it. In the labels array the singular and plural form of the name is needed. The public switch set to true allows the users to use the post type on the admin. The has_archive sets the option to use archive of post types.

<?php
add_action( 'init', 'random_quote' );
function random_quote() {
	register_post_type( 'random_quote',
		array(
			'labels' => array(
				'name' => __( 'Random Quotes' ),
				'singular_name' => __( 'Random Quote' )
			),
			'public' => true,
			'has_archive' => true,
		)
	);
}
?>

3. Creating Admin Interface

With project_edit_columns and project_custom_columns function we can create a modified admin interface for the custom post type using the Person and Quote fields (overriding the title and description). Both of these two functions are needed to get the job done.

<?php
add_filter("manage_edit-random_quote_columns", "project_edit_columns");

function project_edit_columns($columns) {
	$columns = array(
		"cb" => "<input type=\"checkbox\" />",
		"title" => "Person",
		"description" => "Quote",
	);

	return $columns;
}

add_action("manage_posts_custom_column",  "project_custom_columns");

function project_custom_columns($column) {
	global $post;
	switch ($column) {
		case "description":
			the_excerpt();
			break;
	}
}
?>

This is a picture of the final plugin.

Listing of custom posts (quotes)

4. Get One Random Quote From the Database

Get data from the WP DB

With the WP_Query class we can get one random element from the custom posts. Because we retrieve only one element we don't need a standard loop. Setting these three arguments are mandatory. The $quo variable helps in creating a string based on the quote and its author which can generate a sample like this:

"I never think of the future. It comes soon enough."
~ Albert Einstein

<?php
function ab_arq_generate() {
	// Retrieve one random quote
	$args = array(
		'post_type' => 'random_quote',
		'posts_per_page' => 1,
		'orderby' => 'rand'
	);
	$query = new WP_Query( $args );

	// Build output string
	$quo = '';
	$quo .= $query->post->post_title;
	$quo .= ' said "';
	$quo .= $query->post->post_content;
	$quo .= '"';

	return $quo;
}
?>

5. Assigning the Quote to the Blog Description Element

To attach the generated quote to its place we use a helper function, and after that we override the default filter (bloginfo).

<?php
function ab_arq_change_bloginfo( $text, $show ) {
	if( 'description' == $show ) {
		$text = ab_arq_generate();
	}
	return $text;
}

add_filter( 'bloginfo', 'ab_arq_change_bloginfo', 10, 2 );
?>

6. Final Code

Here is what we have done, just one file.

<?php
/*
Plugin Name: Adam's Random Quote
Version: 2.0
Plugin URI: http://burucs.com
Description: Loads a Random Quote from custom post types
Author: Adam Burucs
Author URI: http://burucs.com
*/

// Register custom post type
add_action( 'init', 'ab_arq_random_quote' );
function ab_arq_random_quote() {
	register_post_type( 'random_quote',
		array(
			'labels' => array(
				'name' => __( 'Random Quotes' ),
				'singular_name' => __( 'Random Quote' )
			),
			'public' => true,
			'has_archive' => true,
		)
	);
}

// Create admin interface

add_filter("manage_edit-random_quote_columns", "ab_arq_project_edit_columns");

function ab_arq_project_edit_columns($columns) {
	$columns = array(
		"cb" => "<input type=\"checkbox\" />",
		"title" => "Person",
		"description" => "Quote",
	);

	return $columns;
}

add_action("manage_posts_custom_column",  "ab_arq_project_custom_columns");

function ab_arq_project_custom_columns($column) {
	global $post;
	switch ($column) {
		case "description":
			the_excerpt();
			break;
	}
}

// Main function to get quotes
function ab_arq_generate() {
	// Retrieve one random quote
	$args = array(
		'post_type' => 'random_quote',
		'posts_per_page' => 1,
		'orderby' => 'rand'
	);
	$query = new WP_Query( $args );

	// Build output string
	$quo = '';
	$quo .= $query->post->post_title;
	$quo .= ' said "';
	$quo .= $query->post->post_content;
	$quo .= '"';

	return $quo;
}

// Helper function
function ab_arq_change_bloginfo( $text, $show ) {
	if( 'description' == $show ) {
		$text = ab_arq_generate();
	}
	return $text;
}

// Override default filter with the new quote generator
add_filter( 'bloginfo', 'ab_arq_change_bloginfo', 10, 2 );
?>

7. Summary

In just a few additional steps we created a lot more flexible storing system with the use of custom posts, however please note that if you deactivate or delete the plugin, the quotes (custom posts) will remain in the WordPress database. If you want these to be deleted you have to extend this plugin accordingly.

Related Posts
  • Code
    Creative Coding
    Advanced Use of Attachments in WordPress: Creating Custom Queries for AttachmentsAdvanced use of attachments in wordpress 400
    This tutorial is the second in a four part series in which you'll learn some techniques for working with images in attachments in WordPress which give you advanced options.Read More…
  • Code
    Creative Coding
    Using a Custom Post Type to Create a Home Page BannerUsing a custom post type to create a home page banner
    Sometimes it's useful to have a nice obvious banner on your site's home page—for announcements, snippets that aren't long enough to merit a blog post, or links to new content within the site. But you don't want to be editing your homepage content every time you add a new piece of content, nor do you want to be delving into the code to add content.Read More…
  • Code
    Plugins
    Using HighCharts in WP-AdminHighcharts 400
    Charts are a great way to present data. They make data more digestible by making it visually appealing. In WordPress, there is no built-in method for getting posts and pages data in a graphical form. Although, there are certain plugins available which integrate Google Analytics with WordPress, but they are overkill if you want to get only a portion of that data. Also, nothing should keep you from learning new techniques and to dive straight into the subject is the best way to learn.Read More…
  • Code
    Creative Coding
    Customizing the WordPress Admin - Listings ScreensCustomize wordpress admin rachel 400
    In Parts 1-4 of this series I showed you how to: Customize the WordPress login screen Customize the dashboard Customize the admin menu Add help text to post editing screens In this fifth instalment I'll show you how to customize listings screens in the admin.Read More…
  • Code
    Plugins
    Create a Shortcode to List Posts With Multiple ParametersPost listing shortcode main image400
    On many of the client sites I build, I find there are times when I need to include a post listing on a page. I'm not talking about archive pages here, but adding a custom listing to an existing static page. For example, I might want to list some posts on the 'About' page, or the site may require an in-depth page for a topic, with a list of posts and custom post types related to that topic. One way to do this is by creating a custom page template to include the current page content plus the results of a second custom query, but if you want more flexibility over how you list posts, or just want to do it a few times, a shortcode will be a simpler solution. In this tutorial, I'll show you how to create a simple shortcode to list all posts of a custom post type, and then I'll expand on that to create a shortcode with various parameters that users can specify to list posts however they want.Read More…
  • Code
    Plugins
    Creating Client Testimonials With Custom Post TypesCreating client testimonials with custom post types
    If you're running any type of business online, it's a good idea to get your clients' opinions on what they thought about the services you provided. First of all, this can benefit you by giving you feedback on how you can improve aspects of your business, but most of all, it can give you great testimonials, which can help to persuade potential clients to use your services.Read More…