Add Snippet To Project
Have you ever wanted to draw attention to certain posts or pages in the WordPress admin area? One way to do this is by highlighting the post states, such as "Featured" or "New," with a custom color. In this article, we’ll show you how to easily add your own post states and style them to make them stand out in the admin dashboard. Let’s dive in!
function wpturbo_highlight_post_states( $post_states, $post ) {
if ( 'publish' === $post->post_status ) {
$post_states['highlight'] = __( 'Highlight This Post', 'wpturbo' );
}
return $post_states;
}
add_filter( 'display_post_states', 'wpturbo_highlight_post_states', 10, 2 );
The function defined in this code snippet, wpturbo_highlight_post_states()
, adds a custom post state to certain posts within the WordPress admin area. In this case, the post state is labeled "Highlight This Post".
The function takes two parameters: $post_states
, which contains an array of all the current post states, and $post
, which represents the current post object being displayed.
We begin by checking if the current post is in the "publish" status using an if
statement. If the post is published, we add our custom post state to the $post_states
array using the key highlight
and providing it with the value __( 'Highlight This Post', 'wpturbo' )
. This value will be shown on the post within the WordPress admin area to identify that it is a highlighted post.
__( 'Highlight This Post', 'wpturbo' )
is a WordPress function used for localization. It makes sure that the text "Highlight This Post" will be properly translated when the site is being displayed in a different language. The second parameter, ‘wpturbo’, is a text domain used to identify the plugin or theme that the translation string belongs to.
Lastly, we use the add_filter()
function to hook wpturbo_highlight_post_states()
into the display_post_states
filter at a priority of 10 (arbitrary) with two arguments. The display_post_states
filter lets us modify the post states that are displayed for each post within the WordPress admin area.
With this code, any published posts within the WordPress admin area will now have a "Highlight This Post" state displayed next to them, giving the admin user an easy way to identify the highlighted posts.