Here is a quick — and reusable — way to make the post editing experience more intuitive for your authors. Say you have a custom post type called “Team Members”. When an author goes to create a new Team Member, the first field they will probably fill out is the team member’s name and will be met with a slightly unhelpful placeholder text. I think “Enter title here” is a bit misleading for a team member. Something like “Team Member name” would be more appropriate.
First Approach
I did a quick Google search to find how others have modified the title field placeholder text and found a few variations of this function:
<?php | |
add_filter( 'enter_title_here', function( $title ) { | |
$screen = get_current_screen(); | |
if ( 'your_custom_post_type' == $screen->post_type ){ | |
$title = 'Your custom placeholder text'; | |
} | |
return $title; | |
} ); |
While it works you will end up with several if
statements, one for each custom post type, which could get messy on complex sites. But the bigger issue for me is that the function above is not reusable because project-specific data is embedded in the function itself. A better approach would be to abstract the data away so that we can reuse the function without ever rewriting it.
Second Approach
It turns out that you can add custom arguments when registering a custom post type. I added the argument 'title_placeholder'
(see this Gist). With that argument in place all that needs to be done is check whether it is set and replace the default title field placeholder text if so:
<?php | |
add_filter( 'enter_title_here', 'prefix_change_title_placeholder_text' ); | |
/** | |
* Change the placeholder text for the post title field. | |
* | |
* @param string $title Default placeholder text. | |
* @return string | |
*/ | |
function prefix_title_placeholder_text( $title ) { | |
$post_type_object = get_post_type_object( get_post_type() ); | |
if ( empty( $post_type_object->title_placeholder ) ) { | |
return $title; | |
} | |
return $post_type_object->title_placeholder; | |
} |
With this approach I can keep all of my project specific data in a configuration file and never need to modify the function. If the config concept is new to you I recommend reading Alain Schlesser’s series on using a config for reusable code.
Leave a Reply