WP Smith

Creating WordPress & Genesis Websites Since 2010

  • Home
  • About
  • Services
  • Blog
  • Contact

Jan 03 2013

Disable AutoSave on Add New Post Admin Page

Disabling revisions won't stop WordPress from creating the initial draft version of a custom post type. So I used this snippet to accomplish this as well.

<?php
add_action( 'admin_enqueue_scripts', 'wps_cpt_admin_enqueue_scripts' );
/**
* Disable initial autosave/autodraft
*/
function wps_cpt_admin_enqueue_scripts() {
if ( 'cpt' == get_post_type() )
wp_dequeue_script( 'autosave' );
}
view raw wps_cpt_admin_enqueue_scripts.php hosted with ❤ by GitHub

Written by Travis Smith · Categorized: Custom Post Types

Jul 03 2012

How to Reserve Slugs for WordPress Custom Post Types

If you are using a plugin (or two or three) that do not prefix (improperly I might add!) their custom post types (e.g., downloads from WordPress Download Monitor, listings from AgentPress Listings, etc.) with a namespace like (wps_portfolio, etc.). Or maybe you didn't know and you were using a GUI Custom Post Type plugin. So now you possibly have an archive page of http://domain.com/downloads or http://domain.com/portfolio or http://domain.com/listings.

However, if you have pages, you possibly could have a conflict where a page was created titled Portfolio. So its slug or URI becomes http://domain.com/portfolio (or a page called Listings and have http://domain.com/listings). This can lead to all sorts of issues!!! Issues with content going missing or page displaying improperly. Etc. If you didn't know this was the case, then you may not know to look here, and if you do eventually find out, hours have gone by in frustration, angst, and hatred towards WordPress grows even though it was clearly a user error.

So how do you prevent this? Simple. Two filters: wp_unique_post_slug_is_bad_hierarchical_slug & wp_unique_post_slug_is_bad_flat_slug. These filters are applied when wp_unique_post_slug() runs to check a post's slug. So hooking into that filter enables you to block whatever slugs you'd like preventing pages or any other custom post type from using that name.

Recently, for a plugin I developed, I registered a taxonomy so that the url would be similar to pages. So if a person entered "Fun Times" as a term, the URL would be http://domain.com/fun-times/ which could potentially conflict with a page called "Fun Times" (URL would also be http://domain.com/fun-times/). So to help WordPress recognize this, I wrote a simple function:
[php]<?php
add_filter( 'wp_unique_post_slug_is_bad_hierarchical_slug', 'k12_is_bad_slug', 10, 2 );
add_filter( 'wp_unique_post_slug_is_bad_flat_slug', 'k12_is_bad_slug', 10, 2 );
/**
* Checks "post" slugs for potential conflicts with my new custom post type
* Return true to block slug, false to "approve" the slug
*
* @param boolean $is_bad_slug Default false.
* @param string $slug Slug in question
* @return boolean $is_bad_slug True if slug matches a taxonomy term
*/
function k12_is_bad_slug( $is_bad_slug, $slug ) {
if ( get_terms( 'k12_worksheet_type', array( 'hide_empty' => false, 'slug' => $slug ) ) || 'worksheet' == $slug || 'worksheets' == $slug )
return true;
return $is_bad_slug;
}
[/php]

wp_unique_post_slug_is_bad_hierarchical_slug can also pass 2 more arguments: $post_type (string, post type registered name), $post_parent (int, post parent post ID) & wp_unique_post_slug_is_bad_flat_slug can also pass 1 more argument: $post_type (string, post type registered name).

So let me explain this briefly. The conditional statement is checking 3 things: terms, and two hardcoded slugs ("worksheet" and "worksheets"). To check the terms, I use get_terms() to search all terms (hide_empty = false) in k12_worksheet_type taxonomy for the slug ($slug) in question.

This was first brought to my attention when I came across Rachel Carden's Post How to Define Reserve Slugs for WordPress Posts and Pages.

Written by Travis Smith · Categorized: Custom Post Types

Apr 10 2012

Registering Multiple Custom Post Types

Nick Croft has a great post, Custom Post Types Made Easy, on registering multiple custom post types that I have expanded for my purposes.

On almost every install of WordPress I do, I now have at least 2 custom post types: Tweets and Bookmarks.

Since I have this in a plugin, I am using a constant for my URL base:
[php]define( 'WPSPS_URL', WP_CONTENT_URL . '/themes/my-child-theme-folder' );[/php]

First, there is the creation function. This creation function, which I call wps_create_post_types() is the only function that I ever edit, really append.
[php]
add_action( 'init' , 'wps_create_post_types' );
/**
* Create Post Types
*
* @link http://codex.wordpress.org/Function_Reference/register_post_type
*
*/
function wps_create_post_types() {
$post_types = array(
'Tweet' => array(
'rewrite' => array( 'slug' => 'tweets' ),
'menu_icon' => WPSPS_URL . '/lib/images/tweets_16x16.png',
'description' => 'Twitter Archive (@wp_smith)',
'supports' => array( 'title', 'editor', 'custom-fields', 'post-formats' ),
'taxonomies' => array( 'category' , 'post_tag' , ),
),
'Bookmark' => array(
'rewrite' => array( 'slug' => 'tweets' ),
'description' => 'Bookmarks',
'supports' => array( 'title', 'thumbnail', ),
'menu_icon' => WPSPS_URL .'/lib/images/bookmarks16x16.png',
'taxonomies' => array( 'wps_bookmark_category', 'wps_bookmark_tags' ),
),
);
foreach ( $post_types as $title => $args ) {
wps_register_post_type( $title , $args );
}
}
[/php]

So what's going on here is that I am cycling through the post types array registering each post type with a helper function called wps_register_post_type(). Note that I am calling this main function in the init hook, which is required for custom post type registration. So every time I add a new post type I am adding the following:
[php]
'CPT Name' => array(
'post_type' => '', // String
'description' => '', // String
'rewrite' => array( 'slug' => 'cpt-names' ), // Array with 'slug'
'menu_icon' => WPSPS_URL .'/path/to/my/images/bookmarks16x16.png', // String URL
'supports' => array( 'title', 'editor', 'excerpt', 'revisions', 'thumbnail', 'page-attributes', 'custom-fields' ), // Array of strings = features
'taxonomies' => array( 'category', 'post_tag', ),// Array of strings = taxonomies
),
[/php]

First, while I never have to do this (because this is my code and I've set it up how I like it), you can add a post_type entry to your array. This is the name of the registered post type. If you didn't, the helper functions would do it for you. In this case, 'CPT Name' would be registered as wps_cpt_names. It converts the name to lower case and replaces the spaces with underscores. Note, my custom post type name is always my singular title, so if I want to pluralize the slug, then I add a rewrite entry to the array. On all my custom post types I add a menu_icon (call me Vain!), and since custom post types vary, I add my own support entry to the array. However, there does exist a default if you want everything. If I want my custom post type to support some Genesis functionality, I would include them here (e.g., 'genesis-seo', 'genesis-layouts', 'genesis-simple-sidebars').

[php]
/**
* Registers a post type with default values which can be overridden as needed.
*
* @author Nick the Geek
* @author Travis Smith
* @link http://designsbynickthegeek.com/tutorials/custom-post-types-made-easy
* @link http://codex.wordpress.org/Function_Reference/register_post_type
* @link https://wpsmith.net/2012/custom-post-types/registering-multiple-custom-post-types
*
* @uses sanitize_title() WordPress function that formats text for use as a slug
* @uses wp_parse_args() WordPress function that merges two arrays and parses the values to override defaults
* @uses register_post_type() WordPress function for registering a new post type
*
* @param string $title title of the post type. This will be automatically converted for plural and slug use
* @param array $args overrides the defaults
* @param string $prefix prefix string
*/
function wps_register_post_type( $title, $args = array() ) {
$prefix = 'wps_';
$sanitized_title = sanitize_title( $title );
$plural_title = isset( $args['plural_title'] ) ? $args['plural_title'] : '';
unset( $args['plural_title'] );

$defaults = array(
'labels' => wps_post_type_labels( $title , $plural_title ),
'_builtin' => false,
'description' => $title . __( ' Custom Post Type' , 'child-translate-domain' ),
'menu_position' => 6, // WP default: null (below comments ~ 25)
'menu_icon' => '', // WP default: null
'public' => true, // WP default: true
'publicly_queryable' => true, // WP default: value of 'public'
'show_ui' => true, // WP default: value of 'public'
'show_in_nav_menus' => true, // WP default: value of 'public'
'show_in_menu' => true, // WP default: null; 'show_ui' must be true
'has_archive' => true, // WP default: false
'capability_type' => 'post', // WP default: post; defines 'capabilities' as well
'map_meta_cap' => false, // WP default: false
'hierarchical' => false,
'taxonomies' => array(),
'rewrite' => array( 'slug' => $sanitized_title ),
'query_var' => true,
'can_export' => true,
'supports' => array( 'title' , 'editor' , 'excerpt' , 'author' , 'comments' , 'custom-fields' , 'revisions' , 'thumbnail' , 'genesis-seo' , 'genesis-layouts' , 'genesis-simple-sidebars' ),
);

$args = wp_parse_args( $args, $defaults );

// Correct show_in_menu arg
if ( false === $args['show_ui'] && true === $args['show_in_menu'] )
$args['show_in_menu'] = false;

$post_type = isset( $args['post_type'] ) ? $args['post_type'] : $prefix . str_replace( '-', '_', $sanitized_title) . 's';

register_post_type( $post_type, $args );

}
[/php]

While the PHP documentation makes the function self-explanatory, let me explain in a bit more detail. First, I sanitize the title, which formats text for use as a slug. So if the title is: "This Is the Title of My Post," the resulting sanitized title would be: "this-is-the-title-of-my-post." This is important because case and spacing matters.

Then for the arguments, I have a list of default arguments that I use, which basically match the WordPress defaults (and an argument could be made against having them at all). However, I include everything (except capabilities, permalink_epmask, and register_meta_box_cb) so you can see everything that you need or may want.

Next, I am getting my labels from another helper function called wps_post_type_labels()
[php]
/**
* A helper function for generating localizable labels
*
* @author Travis Smith
* @uses _x() WordPress function that retrieves translated string with gettext context
* @uses __() WordPress function that retrieves the translated string from the translate()
*
* @param string $singular Singular Title/Label
* @param string $plural Plural Title/Label (optional)
*/
function wps_post_type_labels( $singular, $plural = '' ) {
if ( $plural == '' ) $plural = $singular . 's';

return array(
'name' => _x( $plural, 'post type general name', 'child-translate-domain' ),
'singular_name' => _x( $singular, 'post type singular name', 'child-translate-domain' ),
'add_new' => __( 'Add New' , 'child-translate-domain' ),
'add_new_item' => __( 'Add New '. $singular , 'child-translate-domain' ),
'edit_item' => __( 'Edit '. $singular , 'child-translate-domain' ),
'new_item' => __( 'New '. $singular , 'child-translate-domain' ),
'view_item' => __( 'View '. $singular , 'child-translate-domain' ),
'search_items' => __( 'Search '. $plural , 'child-translate-domain' ),
'not_found' => __( 'No '. $plural .' found' , 'child-translate-domain' ),
'not_found_in_trash' => __( 'No '. $plural .' found in Trash' , 'child-translate-domain' ),
'parent_item_colon' => ''
);
}
[/php]

This helper labels function pluralizes my labels for me unless I specify a plural label myself, and makes all the strings compatible for localization, which if you are not making your custom post types labels able to be translated, then you need to be. Some of you may say that you never have the need; however, if you get in the practice of localizing, then when you do have the need, your code is already ready/done instead of having to re-invest the work later (which really is more work).

Now, if you want to add Genesis functionality to existing custom post types (that you may have registered via another plugin), then you may need the following.
[php]
add_action( 'init', 'wps_add_post_type_support' );
/**
* Add Genesis custom support for registered post types
* Add Genesis SEO/Layout support to CPTs (if not registered with them)
*
* @uses add_post_type_support() Registers support of certain features for a given post_type
* @link http://codex.wordpress.org/Function_Reference/add_post_type_support
*
*/
function wps_add_post_type_support() {
// Uncomment below as appropriate
//add_post_type_support( 'post_type', 'genesis-seo' );
//add_post_type_support( 'post_type', 'genesis-layouts' );
//add_post_type_support( 'post_type', 'genesis-simple-sidebars' );
}
[/php]

To add the above to multiple post types:
[php]
add_action( 'init', 'wps_add_post_type_support' );
/**
* Add Genesis custom support for registered post types
* Add Genesis SEO/Layout support to CPTs (if not registered with them)
*
* @uses add_post_type_support() Registers support of certain features for a given post_type
* @link http://codex.wordpress.org/Function_Reference/add_post_type_support
*
*/
function wps_add_post_type_support() {
$pts = array( 'post_type1', 'post_type2' );
foreach( $pts as $pt ) {
// Uncomment below as appropriate
//add_post_type_support( $pt, 'genesis-seo' );
//add_post_type_support( $pt, 'genesis-layouts' );
//add_post_type_support( $pt, 'genesis-simple-sidebars' );
}
}
[/php]

Written by Travis Smith · Categorized: Custom Post Types

Apr 10 2012

Add Genesis SEO, Layouts, & Sidebars to Custom Post Types

Now, if you want to add Genesis functionality, that is, Genesis SEO, Layouts, & Sidebars, to existing custom post types (that you may have registered via another plugin), then you need the following.
[php]
add_action( 'init', 'wps_add_post_type_support' );
/**
* Add Genesis custom support for registered post types
* Add Genesis SEO/Layout support to CPTs (if not registered with them)
*
* @uses add_post_type_support() Registers support of certain features for a given post_type
* @link http://codex.wordpress.org/Function_Reference/add_post_type_support
*
*/
function wps_add_post_type_support() {
// Uncomment below as appropriate
//add_post_type_support( 'post_type', 'genesis-seo' );
//add_post_type_support( 'post_type', 'genesis-layouts' );
//add_post_type_support( 'post_type', 'genesis-simple-sidebars' );
}
[/php]

To add the above to multiple post types:
[php]
add_action( 'init', 'wps_add_post_type_support' );
/**
* Add Genesis custom support for registered post types
* Add Genesis SEO/Layout support to CPTs (if not registered with them)
*
* @uses add_post_type_support() Registers support of certain features for a given post_type
* @link http://codex.wordpress.org/Function_Reference/add_post_type_support
*
*/
function wps_add_post_type_support() {
$pts = array( 'post_type1', 'post_type2' );
foreach( $pts as $pt ) {
// Uncomment below as appropriate
//add_post_type_support( $pt, 'genesis-seo' );
//add_post_type_support( $pt, 'genesis-layouts' );
//add_post_type_support( $pt, 'genesis-simple-sidebars' );
}
}
[/php]

Written by Travis Smith · Categorized: Custom Post Types

Jan 06 2012

Developing a Custom Post Type and a Custom Taxonomy in Genesis with Custom Pages, Part 5

Now, in Developing a Custom Post Type and a Custom Taxonomy in Genesis with Custom Pages, Part 1, we have the registration of the custom post type, custom taxonomy and the addition of the metaboxes. In Part 2, we discussed the Single Page Template for the custom post type. In Part 3, we discussed the Taxonomy Template for the custom taxonomy. In Part 4, we discussed the a page template for the custom post type.

Now this tutorial will discuss Creating Columns in the Edit Custom Post Page. Justin Tadlock has an excellent post on this and is a must read: Custom columns for custom post types. For those, however, who don't like coding, there is a good plugin that will do this work for you. Pippin's Post Type Column Editor from Code Canyon (affil link) is only $12 and worth the money, if you just lovehate coding.

Column Editor

Before, I move forward to how to do this via php and functions.php, let me highlight Pippin's plugin (so if you care about the code skip this and the pictures). With post Type Column Editor you can easily customize the dashboard columns for all your post types. So if you wanted to add thumbnails and excerpts to the columns of posts and/or pages (if pages supports excerpts), then you can easily add it with a few clicks. This plugin gives you a really easy to use way to modify and manage the table columns for your post types. You can display post type entry titles, categories, tags, excerpts, authors, custom meta fields, thumbnails, and custom taxonomies. You can customize the columns for each built-in and custom post type separately with a straight forward drag-and-drop interface.

So when you first register a custom post type, here is what you'll see:

Custom Post Type with No Columns
Initial Custom Post Type

Then when you use the Post Type Column Editor, you see your various options.

Post Type Column Editor Options
Post Type Column Editor Options

For a demonstration check out this Screenr:

This obviously works well with his Easy Content Types plugin which outputs PHP code for you to embed into your plugin and/or theme.

Sometimes it becomes necessary to display more than the usual Title and Date of our post types. In this case, we want to add a new column to the edit post page to allows us to easily see which axle size our disc brakes belong to. There are some great examples of how to do that but below is an example of how we can add our axle size to the page.

First we must add the column. Use the code below and add it to our wps-admin-functions.php file.

[php]
// Add Columns for Disc Brakes Edit Posts Page
add_filter( 'manage_edit-wps_discbrakes_columns', 'wps_discbrakes_columns' ) ;
function wps_discbrakes_columns($column) {
$column = array(
'cb' => '<input type="checkbox" />',
'title' => __( 'Disc Brakes' ),
'axlesizes' => __( 'Axle Sizes' ),
'date' => __( 'Date' )
);
return $column;
}
[/php]

If we save this file and upload it, we will now see a new column called Axle Sizes. This is great but there is no content in this column. Now we need to go get the content and display here. Use this code below to do just that.

[php]
// Gets the Taxonomy Terms and retunrs them on the Disc Brakes Edit Posts Page
add_action( 'manage_wps_discbrakes_posts_custom_column', 'manage_wps_discbrakes_columns', 10, 2 );
function manage_wps_discbrakes_columns( $column, $post_id ) {
global $post;
switch( $column ) {
case 'axlesizes' :
$terms = get_the_terms( $post_id, 'wps_axlesizes' );
if ( !empty( $terms ) ) {
$out = array();
foreach ( $terms as $term ) {
$out[] = sprintf( '<a href="%s">%s</a>', esc_url( add_query_arg( array( 'post_type' => $post->post_type, 'wps_axlesizes' => $term->slug ), 'edit.php' ) ), esc_html( sanitize_term_field( 'name', $term->name, $term->term_id, 'wps_axlesizes', 'display' ) ) );
}

echo join( ', ', $out );
} else {
_e( 'No Axle Sizes' );
}

break;

default :
break;
}
}
[/php]

The code above allows us to select one of the axle sizes and it will only display the disc brakes for that size.
Custom Column for Custom Post Type

Written by Travis Smith · Categorized: Custom Post Types, Genesis

  • 1
  • 2
  • 3
  • …
  • 6
  • Next Page »
  • Twitter
  • Facebook
  • LinkedIn
  • Google+
  • RSS

Copyright © 2025 � WP Smith on Genesis on Genesis Framework � WordPress � Log in