Tales
Tales

Reputation: 1923

How to add a custom post type in my OOP plugin?

I require to create a custom post type for a plugin. Well, I decided to create the plugin in an OOP way, so basically I used the WordPress-Plugin-Boilerplate by Devin Vinson as starter point.

I have seen many plugins which add the custom post type in the main plugin file like this:

add_action( 'init', 'create_my_custom_post_type' );
function create_my_custom_post_type(){
    $labels = array( ... );
    $args   = array( ... );
    register_post_type( 'my_custom_post_type', $args );
}

Now, since I am trying to do it the right way, instead of doing that, I went to the file class-plugin-name.php inside de /includes directory and created a new private function like this:

class Plugin_Name {
    private function register_my_custom_post_type(){
        $labels = array( ... );
        $args   = array( ... );
        register_post_type( 'my_custom_post_type', $args );
    }

    public function __construct(){
        // This was also added to my constructor
        $this->register_my_custom_post_type();
    }
}

Since this is run every time the plugin is called, I figured the post type would perfectly be created, but I am getting this error:

Fatal error: Call to a member function add_rewrite_tag() on a non-object in /public_html/wordpress/wp-includes/rewrite.php on line 51

I am pretty sure the problem is my new function, anyone has any ideas on how to do it correctly? Maybe I should put the code outside that class and just create a new class and create a hook for init?

Upvotes: 1

Views: 2939

Answers (1)

diggy
diggy

Reputation: 6828

You're right about hooking into init to register you custom post type. Here's the correct syntax:

public function __construct() {
    add_action( 'init', array( $this, 'register_my_custom_post_type' ) );
}

Upvotes: 4

Related Questions