Random Quote Plugin With Custom Post Type

Random Quote Plugin With Custom Post Type

Tutorial Details
  • Program: WordPress
  • Version: 3.0+
  • Difficulty: Medium
  • Estimated Completion Time: 30 minutes

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.

Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Pingback: Random Quote Plugin With Custom Post Type | Qtiva

  • http://www.derby-webdesign.co.uk Derby Web Design

    Nice plugin, I’ll give it a try. Should come in handy :)

  • http://prop-14.com Randy

    I like simple, to the point, tutorials like this one.

    “Because we retrieve only one element we don’t need a standard loop”

    To clarify, that means you can’t use regular post functions like the_title(), etc.
    Correct?

    • janw

      you could if you would set up the loop for this one post.

  • http://www.guideplease.com Dilawer Pirzada

    Hi Adam,

    You described about Random Quote Plugin in very depth. Thanks for this! I may be able to do this at all.

    Basically, now-a-days I was looking for a plugin that makes my background images used in my theme, in one CSS sprite automatically just after activating it. As Facebook the biggest social network uses css sprites.

    Here, on WordPress a plugin is available, related to this query but it’s not working accurately how it should be.

    The name of the plugin is: cSprites – Speed Up Page Load Time with Dynamic Image Sprites

    When I install and activate this plugin, it pops up some database errors on the homepage.

    Actually, I really want this plugin as my website is not loading very fast, and when I check my website speed on Gtmetrix, there I have 67% means C grade.

    Gtmetrix tells me what I need to do? There most recent F grade error is to combine images using css sprites. What should I do?

    As I’m not very well in web based languages, i.e CSS, HTML, PHP, MySql, etc. Please, do something about this issue. I mean to say, I request you to make a plugin that allow me to add automatically CSS sprites in my Theme.

    Hope you understand. If you provide me this type of plugin, I’ll do my best to promote it too with my friends and also write a post on it in my blog.

  • http://www.xpertdeveloper.com Avinash

    nice!!!!! keep it up….

  • http://www.layerbag.com Claude Meri

    I really like this type of simple and yet effective tutorials.

    Thanks Adam.

  • http://www.learneveryday.net arifur rahman

    the database structure image is so small and not able to view. Please provide clear image to watch. other wise it is use less.

  • http://www.basicwp.com Basic WP

    That is very neat to the point and very useful code. Gonna use in future project. Thanks!

  • http://helpfolder.com Mahesh

    Thanks. I can give some twist to this like – jquery fader quotes or quote slider. Lots of things to do with quotes ;)

  • Mark

    Could you clarify one thing for me, in the helper function you to see if the $show variable equals the string ‘description’ before running the quote generator, is this parameter automatically passed into function when it’s run through the ‘bloginfo’ filter? Thanks

  • Pingback: test | dentalcyberweb.com

  • Pingback: dentalcyberweb.com

  • Bram

    Hi, thanks for this excellent tutorial!

    I would like to alter this code so it queries once a week for a new quote, so there will be a random quote of the week. Does anyone know a tutorial that might help me to accomplish this? (I’m fairly new to php…)

  • Pingback: Tutorials Που Θα Σας Βοηθήσουν Να Δημιουργήσετε Το Πρώτο Σας WP Plugin | Ελληνική Κοινότητα WordPress

  • Pingback: MikeKeller.name | WordPress Plugin Writing Tutorials

  • Pingback: 30 Useful Tutorials to Create WordPress Plugin | Doublemesh