Random Quote Plugin With Custom Post Type

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.


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.


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.

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


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).


6. Final Code

Here is what we have done, just one file.


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.

Tags:

Comments

Related Articles