search
HomeCMS TutorialWordPressWordPress Custom Post Types - Notices and Taxonomies

WordPress Custom Post Types - Notices and Taxonomies

Key Takeaways

  • Customizing admin notices for WordPress Custom Post Types (CPT) can be achieved by using the ‘post_updated_messages’ hook, which allows users to change the default alert message displayed when a post is saved, published, or updated.
  • In WordPress, taxonomies serve as a mechanism for grouping posts of any type, including CPTs. Custom taxonomies can be created using the ‘register_taxonomy()’ function, allowing for more specific categorization of CPTs.
  • Custom Post Types and taxonomies are powerful WordPress features that allow for more organized and specific grouping of data or post entries beyond the default post and page types.

In my previous post, I introduced Custom Post Types (CPT) and how to create one for your WordPress powered website.

We also took a look at how to customize the various UI labels of a custom post type to make it distinct from the native post and page post types. However, we didn’t cover how to customize the admin notices generated by them.

In this tutorial, I will be covering how to customize these notices and also how to register new taxonomies to a custom post type.

Customizing CPT Admin Notices

Are you familiar with the alert message that is displayed near the top of admin pages for example when a post is saved as draft, published or even when you save the settings of a plugin? This message is what is referred to as an admin notice.

By default, the admin notices displayed when working on a custom post assumes you are dealing with a post post type and therefore, when for example a book post type is updated, the following notice is displayed: Post updated. View post.

You can change the text of these messages easily by using the post_updated_messages hook like so:

add_filter( 'post_updated_messages', 'book_cpt_messages' );


/**
 * Book CPT updates messages.
 *
 * @param array $messages Existing post update messages.
 *
 * @return array Amended book CPT notices
 */
function book_cpt_messages( $messages ) {
    $post             = get_post();
    $post_type        = get_post_type( $post );
    $post_type_object = get_post_type_object( $post_type );

    $messages['book'] = array(
        0  => '', // Unused. Messages start at index 1.
        1  => __( 'Book updated.', 'textdomain' ),
        2  => __( 'Custom field updated.', 'textdomain' ),
        3  => __( 'Custom field deleted.', 'textdomain' ),
        4  => __( 'Book updated.', 'textdomain' ),
        5  => isset( $_GET['revision'] ) ? sprintf( __( 'Book restored to revision from %s', 'textdomain' ), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
        6  => __( 'Book published.', 'textdomain' ),
        7  => __( 'Book saved.', 'textdomain' ),
        8  => __( 'Book submitted.', 'textdomain' ),
        9  => sprintf(
            __( 'Book scheduled for: <strong>%1$s</strong>.', 'textdomain' ),
            date_i18n( __( 'M j, Y @ G:i', 'textdomain' ), strtotime( $post->post_date ) )
        ),
        10 => __( 'Book draft updated.', 'textdomain' )
    );

    if ( $post_type_object->publicly_queryable ) {
        $permalink = get_permalink( $post->ID );

        $view_link = sprintf( ' <a href="%s">%s</a>', esc_url( $permalink ), __( 'View book', 'textdomain' ) );
        $messages[ $post_type ][1] .= $view_link;
        $messages[ $post_type ][6] .= $view_link;
        $messages[ $post_type ][9] .= $view_link;

        $preview_permalink = add_query_arg( 'preview', 'true', $permalink );
        $preview_link      = sprintf( ' <a target="_blank" href="%s">%s</a>', esc_url( $preview_permalink ), __( 'Preview book', 'textdomain' ) );
        $messages[ $post_type ][8] .= $preview_link;
        $messages[ $post_type ][10] .= $preview_link;
    }

    return $messages;
}

Code Explanation: The code above customizes admin notices generated by a book custom post type.

The $messages multi-dimensional array controls the admin notices displayed by any post type.

To customize the messages of a book custom post type, create an index array containing the various messages as the value of $messages['book'].

The if statement checks if the custom post type is publicly query-able. That is, whether the public argument is set to true while registering the custom post type.

If true, a link to view a post belonging to the CPT is added to the admin notice displayed when it is updated, published or scheduled for publication while a link to preview the post is added when it is submitted for review or a draft is updated.

Custom Taxonomies

In WordPress, a taxonomy is mechanism for grouping posts of any type.

Examples of taxonomies include Category for grouping posts that are related to a given category and Tag which is pretty similar to categories but is more free form. More information on taxonomies is available over at the WordPress Codex.

That being said, we are going to cover how to create custom taxonomies. Let us take the example of creating a book post type, categorizing the book entries using the same categories used for blog posts isn’t ideal.

A real life example is the Easy Digital Downloads plugin that uses a download custom post type for digital product entries with a download_category taxonomy for product categorization.

To create a custom taxonomy, use the register_taxonomy() function and hook it to the init Action like so:

add_filter( 'post_updated_messages', 'book_cpt_messages' );


/**
 * Book CPT updates messages.
 *
 * @param array $messages Existing post update messages.
 *
 * @return array Amended book CPT notices
 */
function book_cpt_messages( $messages ) {
    $post             = get_post();
    $post_type        = get_post_type( $post );
    $post_type_object = get_post_type_object( $post_type );

    $messages['book'] = array(
        0  => '', // Unused. Messages start at index 1.
        1  => __( 'Book updated.', 'textdomain' ),
        2  => __( 'Custom field updated.', 'textdomain' ),
        3  => __( 'Custom field deleted.', 'textdomain' ),
        4  => __( 'Book updated.', 'textdomain' ),
        5  => isset( $_GET['revision'] ) ? sprintf( __( 'Book restored to revision from %s', 'textdomain' ), wp_post_revision_title( (int) $_GET['revision'], false ) ) : false,
        6  => __( 'Book published.', 'textdomain' ),
        7  => __( 'Book saved.', 'textdomain' ),
        8  => __( 'Book submitted.', 'textdomain' ),
        9  => sprintf(
            __( 'Book scheduled for: <strong>%1$s</strong>.', 'textdomain' ),
            date_i18n( __( 'M j, Y @ G:i', 'textdomain' ), strtotime( $post->post_date ) )
        ),
        10 => __( 'Book draft updated.', 'textdomain' )
    );

    if ( $post_type_object->publicly_queryable ) {
        $permalink = get_permalink( $post->ID );

        $view_link = sprintf( ' <a href="%s">%s</a>', esc_url( $permalink ), __( 'View book', 'textdomain' ) );
        $messages[ $post_type ][1] .= $view_link;
        $messages[ $post_type ][6] .= $view_link;
        $messages[ $post_type ][9] .= $view_link;

        $preview_permalink = add_query_arg( 'preview', 'true', $permalink );
        $preview_link      = sprintf( ' <a target="_blank" href="%s">%s</a>', esc_url( $preview_permalink ), __( 'Preview book', 'textdomain' ) );
        $messages[ $post_type ][8] .= $preview_link;
        $messages[ $post_type ][10] .= $preview_link;
    }

    return $messages;
}

If you have a book custom post type already, you should see the category taxonomy added to the admin menu and post edit screen.

WordPress Custom Post Types - Notices and Taxonomies WordPress Custom Post Types - Notices and Taxonomies

You can also use register_post_type() for registering custom post types, the register_taxonomy() function also accepts an array of arguments for customizing labels and configuration of a custom taxonomy.

I won’t be explaining the arguments because they are pretty much the same as that of register_post_type() . A list of the arguments and descriptions is available here.

Conclusion

Custom Post Types are a powerful feature of WordPress and useful in grouping data or post entries that don’t fit into a post and page type. The icing on the cake is the ability to further categorize the posts of a custom post type by registering a custom taxonomy.

Do you have a question or contribution? Please use the comments to let us know.

Frequently Asked Questions about WordPress Custom Post Types, Notices, and Taxonomies

How can I create a custom post type in WordPress?

Creating a custom post type in WordPress involves adding a few lines of code to your functions.php file. You’ll need to use the register_post_type() function, which allows you to define a new post type by its labels, supported features, availability and other criteria. Remember to flush your rewrite rules after adding the code by visiting the Permalinks settings page.

What are WordPress taxonomies and how do they work?

Taxonomies in WordPress are a way of grouping posts (or custom post types) together. They come in two forms: categories and tags. Categories are hierarchical and can have child categories, while tags are not hierarchical. You can create custom taxonomies using the register_taxonomy() function.

How can I display custom post type notices in WordPress?

To display custom post type notices, you can use the ‘post_updated_messages’ filter hook. This hook allows you to customize the update messages for any post type. You can add a function to your functions.php file that checks the post type and then sets the appropriate message.

How can I associate a custom taxonomy with a custom post type?

When registering a custom taxonomy with the register_taxonomy() function, you can specify the post types that this taxonomy should be associated with. This is done by passing an array of post type names as the second parameter to the function.

What is the ‘post_updated_messages’ hook in WordPress?

The ‘post_updated_messages’ hook in WordPress allows you to customize the messages that are displayed when a post is updated. This can be particularly useful for custom post types, where you might want to display a different message than the default.

How can I use the ‘get_post_type’ function in WordPress?

The ‘get_post_type’ function in WordPress is used to retrieve the post type of the current post or of a given post. It returns a string on success and false on failure. This function can be useful when you need to perform actions based on the post type.

How can I add custom fields to a custom post type in WordPress?

Custom fields can be added to a custom post type in WordPress by using the ‘add_meta_box’ function. This function allows you to add a new meta box to the post editing screen, where you can input additional information for the post.

How can I display custom post types on my site’s front page?

To display custom post types on your site’s front page, you can modify the main query that WordPress uses to display posts. This can be done by using the ‘pre_get_posts’ action hook and setting the ‘post_type’ parameter to the name of your custom post type.

How can I create a custom taxonomy specific to a custom post type?

When registering a custom taxonomy with the register_taxonomy() function, you can specify the post types that this taxonomy should be associated with. This is done by passing an array of post type names as the second parameter to the function.

How can I use the ‘save_post’ action hook in WordPress?

The ‘save_post’ action hook in WordPress is triggered whenever a post or page is created or updated. It can be used to perform actions such as saving post meta data, sending notifications, or other tasks that should happen after a post is saved.

The above is the detailed content of WordPress Custom Post Types - Notices and Taxonomies. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
How to Pass PHP Data and Strings to JavaScript in WordPressHow to Pass PHP Data and Strings to JavaScript in WordPressMar 07, 2025 am 09:28 AM

Best Practices for Passing PHP Data to JavaScript: A Comparison of wp_localize_script and wp_add_inline_script Storing data within static strings in your PHP files is a recommended practice. If this data is needed in your JavaScript code, incorporat

How to Embed and Protect PDF Files With a WordPress PluginHow to Embed and Protect PDF Files With a WordPress PluginMar 09, 2025 am 11:08 AM

This guide demonstrates how to embed and protect PDF files within WordPress posts and pages using a WordPress PDF plugin. PDFs offer a user-friendly, universally accessible format for various content, from catalogs to presentations. This method ens

Is WordPress easy for beginners?Is WordPress easy for beginners?Apr 03, 2025 am 12:02 AM

WordPress is easy for beginners to get started. 1. After logging into the background, the user interface is intuitive and the simple dashboard provides all the necessary function links. 2. Basic operations include creating and editing content. The WYSIWYG editor simplifies content creation. 3. Beginners can expand website functions through plug-ins and themes, and the learning curve exists but can be mastered through practice.

Why would anyone use WordPress?Why would anyone use WordPress?Apr 02, 2025 pm 02:57 PM

People choose to use WordPress because of its power and flexibility. 1) WordPress is an open source CMS with strong ease of use and scalability, suitable for various website needs. 2) It has rich themes and plugins, a huge ecosystem and strong community support. 3) The working principle of WordPress is based on themes, plug-ins and core functions, and uses PHP and MySQL to process data, and supports performance optimization.

Is WordPress still free?Is WordPress still free?Apr 04, 2025 am 12:06 AM

The core version of WordPress is free, but other fees may be incurred during use. 1. Domain names and hosting services require payment. 2. Advanced themes and plug-ins may be charged. 3. Professional services and advanced features may be charged.

How much does WordPress cost?How much does WordPress cost?Apr 05, 2025 am 12:13 AM

WordPress itself is free, but it costs extra to use: 1. WordPress.com offers a package ranging from free to paid, with prices ranging from a few dollars per month to dozens of dollars; 2. WordPress.org requires purchasing a domain name (10-20 US dollars per year) and hosting services (5-50 US dollars per month); 3. Most plug-ins and themes are free, and the paid price ranges from tens to hundreds of dollars; by choosing the right hosting service, using plug-ins and themes reasonably, and regularly maintaining and optimizing, the cost of WordPress can be effectively controlled and optimized.

Should I use Wix or WordPress?Should I use Wix or WordPress?Apr 06, 2025 am 12:11 AM

Wix is ​​suitable for users who have no programming experience, and WordPress is suitable for users who want more control and expansion capabilities. 1) Wix provides drag-and-drop editors and rich templates, making it easy to quickly build a website. 2) As an open source CMS, WordPress has a huge community and plug-in ecosystem, supporting in-depth customization and expansion.

What is the WordPress good for?What is the WordPress good for?Apr 07, 2025 am 12:06 AM

WordPressisgoodforvirtuallyanywebprojectduetoitsversatilityasaCMS.Itexcelsin:1)user-friendliness,allowingeasywebsitesetup;2)flexibilityandcustomizationwithnumerousthemesandplugins;3)SEOoptimization;and4)strongcommunitysupport,thoughusersmustmanageper

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.