2

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( '/', __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

3

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

See WP Codex: https://codex.wordpress.org/Function_Reference/register_post_type

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.

2

I always do it in the init hook. If you do it in setup it every time they change setup or settings you will be registering that post type. Plus if your settings change the url or any portion of the new cpt you'll want those active before you change them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.