0

Why do I need to use the "init" hook instead of the "admin_init" hook?

init:fires after the core of the wordpress is loaded but before headers are sent

admin init:before any other hook when the user accesses the admin area?? so what does that mean exactly? it is certainly after the init hook, is it not?

$args = array(
    'labels' => $labels,
    'public' => true,

);
register_post_type('random', $args);}
add_action('admin_init', 'rdf', 0);
4

The admin_init hook is not fired when viewing pages in the frontend. So hooking register_post_type() to that action will lead to your custom post type (and with that all of its posts) not being available in the frontend at all.

As of Rarst's answer to another question, the admin_init hook gets fired shortly after the init hook, which makes it seem possible to use (with a low value for priority) to register a custom post type for backend only. But the Plugin Handbook says it should be done before.

My suggestion is to use the init hook as generally recommended and only register the post type conditionally when is_admin() is true.

function wpse_254184() {
    if ( is_admin() ) {
        $args = array(
            'labels' => $labels,
            'public' => true,
        );
        register_post_type('random', $args);
    }
}
add_action( 'init', 'wpse_254184' );
  • i get your point but in theory I am talking about registering and accessing it just in the backend? – john-thomas Jan 27 '17 at 2:31
  • @john-thomas: is_admin() doesn't check if the current logged in user in an admin, instead it checks if you are accessing the backend. So CODE in this answer does exactly what you are suggesting "in theory". – Fayaz Feb 13 '17 at 16:21
  • @Fayaz If you chceck times of my edits you will see, that I added that detail in after his comment, in reaction to it. – JHoffmann Feb 13 '17 at 18:06

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.