Register custom_post_type from static function

I am just starting with wordpress plugin development. I want register a new post type when the plugin is activated. But When I activate my plugin nothing happens, no new menu created in the WordPress Desktop, no errors in apache ‘error.log’ file.

I guess thin can be caused because the activate() method is static, but I am trying follow the WordPress.org examples.

I have this:

main-plugin-file.php

register_activation_hook( __FILE__, 'plugin_register_activation_hook' );
function plugin_register_activation_hook(){
    require_once plugin_dir_path( __FILE__ ) . 'includes/class-plugin-activator.php';
    CustomPluginActivator::activate();
}

includes/class-plugin-activator.php

class CustomPluginActivator {
 
    public static function activate() {
        add_action('init', array( get_called_class(), 'register_custom_type'));               
    }
        
    function register_custom_type() {
        register_post_type('custom_type',
            array(
                'labels'      => array(
                    'name'          => __('Names',    'textdomain'),
                    'singular_name' => __('Name',     'textdomain'),
                ),
                'description'   => 'Descripción',
                'public'        => true,
                'menu_position' => 2,
                'has_archive'   => false,
                'rewrite'       => array( 'slug' => 'custom-slug' )
            )
        );
    }

}

Sorry my english. Thanks

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Since the activation hook only will be called when activating the plugin, you will instead need to call register_post_type() on some hook which is triggered every time you access the administration pages. You could use the init hook for this:

add_action('init', array($this, 'register_custom_type'));

You also need to make the register_custom_type() method public for this to work:

public function register_custom_type()
{
  // call register_post_type()
}

Documentation

Note: Post type registrations should not be hooked before the ‘init’
action. Also, any taxonomy connections should be registered via the
$taxonomies argument to ensure consistency when hooks such as
‘parse_query’ or ‘pre_get_posts’ are used.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x