Skip to content

Recent Articles

25
Nov

A Practical Use of Custom Post Types

One thing that I don’t particularly care for is hard-coding snippets of text into themes, especially if there’s a possibility that they may need to be changed down the road. Unfortunately WordPress doesn’t have anything to suit out-of-the-box. With the release of WordPress 3.0, however, custom post types were introduced, which are entirely perfect for this! What I did is add a custom post type of “variable” that are not public, have a UI in the admin and support the title, editor and excerpt. Then I wrote a small function to retrieve the values of these “variables” based upon the title making it easy to pull the data into my theme in however many places I need to without having the same text scattered all over the place. If there is text saved in the excerpt, it will be used, otherwise the main content will be used. Below is what I added to my themes functions.php file, enjoy!

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
add_action( 'init', 'create_variable_post_type' );
function create_variable_post_type() {
    register_post_type( 'variable', array(
        'labels' => array('name' => __( 'Variable' ), 'singular_name' => __( 'Variable' )),
        'public' => false,
        'show_ui' => true,
        'supports' => array('title', 'editor', 'revisions', 'excerpt'),
    ));
}
 
/**
 * Retrieve a variable's value by it's title/key
 *
 * @param string $variable_title Variable Title
 * @return string
 */
function get_variable_value($variable_title) {
	global $wpdb;
	$page = $wpdb->get_var($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE post_title = %s AND post_type= %s", $variable_title, 'variable'));
	if ($page) {
		$object = get_page($page, $output);
		return empty($object->post_excerpt) ? $object->post_content : $object->post_excerpt;
	}
	return null;
}