Why The Init Hook For Custom Post Types

I have a question about this documentation.

Why would I register a Custom Post Type in the init function as the docs suggest? Is this only if I am not using a plugin?

As I understand it, init runs every-time WordPress runs/is-loaded by the user. Doesn’t this mean the site is needlessly re-registering a new post type on every visit? Why not (if building a plugin) register the post type in require_once plugin_dir_path( __FILE__ ) just when the plugin activates?

Wouldn’t that also speed up the site? Or am I interpreting init() wrong? Surely the custom post type persists in the database somewhere so doesn’t have to be called on every init()?

Here is the Custom Post Type example from the docs, using init():

function create_post_type() {
  register_post_type( 'acme_product',
    array(
      'labels' => array(
        'name' => __( 'Products' ),
        'singular_name' => __( 'Product' )
      ),
      'public' => true,
      'has_archive' => true,
    )
  );
}
add_action( 'init', 'create_post_type' );

2 Answers
2

register_post_type function should be executed every time a WP request is made. Default post types don’t have this requirement. You can use your code as is, in MU plugin. Just create a .PHP file with this code, and place it in mu-plugins sub-folder of wp-content. You don’t need to provide any standard plugin headers.

Leave a Comment