How to register custom post types in a plugin?

I’m using toscho’s Plugin Class Demo code as a foundation for a plugin I’m developing. Amongst other things, my plugin registers a custom post type.

public function plugin_setup() {
    $this->plugin_url = plugins_url( "https://wordpress.stackexchange.com/", __FILE__ );
    $this->plugin_path = plugin_dir_path( __FILE__ );
    $this->load_language( 'myplugindomain' );
    // more stuff: register actions and filters
    add_action( 'init', array( 'MyPluginClass', 'register_my_post_types' ) );
}

public function register_my_post_types() {
    $labels = array( ..... );

    $args = array(
        'show_ui' => true,
        'public' => true,
        'labels' => $labels,
        'supports' => array('title', 'editor', 'thumbnail'), 
        'has_archive' => true
    );

    register_post_type('mycustomtype', $args);
}

My question is, is it good practice to hook my register_my_post_types() function to the init hook? Or would it be better to call it directly in the plugin_setup() function?

Thanks in advance

2 Answers
2

The init hook is the first hook allowed. If called earlier it won’t work.

See WP Codex: https://developer.wordpress.org/plugins/post-types/registering-custom-post-types/

Create or modify a post type. register_post_type should only be invoked through the ‘init’ action. It will not work if called before ‘init’, and aspects of the newly created or modified post type will work incorrectly if called later.

Leave a Comment