0
0
WordpressConceptBeginner · 3 min read

What is Init Hook in WordPress: Explanation and Usage

The init hook in WordPress is an action that runs after WordPress has finished loading but before any headers are sent. It is used to initialize code like registering custom post types, taxonomies, or starting sessions early in the page load process.
⚙️

How It Works

The init hook acts like a checkpoint in WordPress's loading process. Imagine WordPress as a factory assembling a webpage. The init hook is the moment when the factory has all its parts ready but hasn't started packaging the final product yet.

At this point, WordPress has loaded all core files and plugins but hasn't sent anything to the browser. This timing lets developers add or change things safely before the page is shown. For example, you can register new content types or prepare data.

Using init is like setting up your workspace before starting a project, ensuring everything you need is ready and in place.

💻

Example

This example shows how to use the init hook to register a custom post type called "Book".

php
<?php
function create_book_post_type() {
    register_post_type('book', [
        'labels' => [
            'name' => 'Books',
            'singular_name' => 'Book'
        ],
        'public' => true,
        'has_archive' => true,
        'rewrite' => ['slug' => 'books'],
        'show_in_rest' => true
    ]);
}
add_action('init', 'create_book_post_type');
Output
Registers a new post type 'Book' accessible in the WordPress admin and on the site under /books/ URL.
🎯

When to Use

Use the init hook when you need to set up things early in WordPress loading but after all plugins and core are ready. Common uses include:

  • Registering custom post types and taxonomies
  • Starting PHP sessions
  • Adding rewrite rules
  • Loading text domains for translations

This hook is ideal for preparing your site’s structure or environment before WordPress sends any output to the browser.

Key Points

  • Runs early: After WordPress loads but before headers are sent.
  • Safe place: To register content types and taxonomies.
  • Multiple uses: Also for sessions, rewrite rules, and translations.
  • Hooks into: WordPress's action system with add_action('init', 'your_function').

Key Takeaways

The init hook runs early in WordPress loading, before output starts.
Use init to register custom post types, taxonomies, and start sessions.
It ensures your code runs after plugins load but before page display.
Add your functions to init with add_action('init', 'function_name').