How to add category and subcategory in WordPress custom code?

The syntax for adding an action in WordPress WITHIN a class is somewhat different. Your code will have to look somewhat more like the following…

class MyPluginClass {

    public function __construct() {

         add_action( 'init', array( $this, 'sample_insert_category') );
    }

    public function sample_insert_category() {

        if(!term_exists('sample-category')) {
            wp_insert_term(
                'Sample Category',
                'category',
                array(
                    'description' => 'This is an sample category.',
                    'slug'        => 'sample-category'
                )
            );
        }

    }
}

$mypluginclass = new MyPluginClass();