Using WordPress ‘registered_post_type’ PHP action

The registered_post_type WordPress action fires after a post type is registered.

Usage

add_action('registered_post_type', 'your_custom_function', 10, 2);

function your_custom_function($post_type, $post_type_object) {
  // your custom code here

  return $post_type;
}

Parameters

  • $post_type (string) – The registered post type.
  • $post_type_object (WP_Post_Type) – Arguments used to register the post type.

More information

See WordPress Developer Resources: registered_post_type

Examples

Log registered post types

Log the name of the registered post types to a file.

add_action('registered_post_type', 'log_registered_post_types', 10, 2);

function log_registered_post_types($post_type, $post_type_object) {
  error_log("Registered post type: " . $post_type . "\n", 3, "/tmp/registered_post_types.log");

  return $post_type;
}

Add a custom capability to a specific post type

Add a custom capability to the ‘book’ post type.

add_action('registered_post_type', 'add_custom_capability', 10, 2);

function add_custom_capability($post_type, $post_type_object) {
  if ($post_type == 'book') {
    $post_type_object->cap->edit_others_posts = 'edit_others_books';
  }

  return $post_type;
}

Modify the post type labels

Change the labels of the ‘movie’ post type.

add_action('registered_post_type', 'modify_movie_labels', 10, 2);

function modify_movie_labels($post_type, $post_type_object) {
  if ($post_type == 'movie') {
    $post_type_object->labels->name = __('Films', 'textdomain');
    $post_type_object->labels->singular_name = __('Film', 'textdomain');
  }

  return $post_type;
}

Add a custom rewrite rule to a post type

Add a custom rewrite rule to the ‘product’ post type.

add_action('registered_post_type', 'add_custom_rewrite_rule', 10, 2);

function add_custom_rewrite_rule($post_type, $post_type_object) {
  if ($post_type == 'product') {
    $post_type_object->rewrite['slug'] = 'shop';
  }

  return $post_type;
}

Display a message after registering a post type

Display a message in the admin area after registering the ‘event’ post type.

add_action('registered_post_type', 'display_message_after_registering_post_type', 10, 2);

function display_message_after_registering_post_type($post_type, $post_type_object) {
  if ($post_type == 'event') {
    add_action('admin_notices', function() {
      echo '<div class="notice notice-success is-dismissible">';
      echo '<p>' . __('Event post type registered successfully!', 'textdomain') . '</p>';
      echo '</div>';
    });
  }

  return $post_type;
}

Tagged in

Leave a Comment

Your email address will not be published. Required fields are marked *