php – how to register custom post type dynamically

I have this code in a custom plugin.

    public function create_new_cpt( WP_REST_Request $request )
    {
        $args = $request->get_param('newCptDetails');

        $cpt = register_post_type( 
            $args['name'], 
            [
                'label' => $args['label'],
                'description' => $args['desc'],
                'show_ui' => true,
                'show_in_menu' => true,
                'show_in_rest' => true
            ]
        );

        if( $cpt ){
            add_option( 'cpt_name', $args['name'] );
            add_option( 'cpt_label', $args['label'] );
            add_option( 'description', $args['desc'] );
            return $cpt;
        } else {
            return 'not registered';
        }
    }

The code is a callback function for a custom REST route that should receive all the required params to create a new CPT. I have done a test but I see that the cpt is not registered and I think it is because I am not calling init hook. In my plugin code I am creating four routes, one is to create a new CPT, another is to list all CPTs and the last two will be used to enable or disable the CPT.

    public function setup_admin_page_routes()
    {

        register_rest_route( 
            $this->namespace, 
            '/list-cpt', 
            [
                'methods' => 'GET',
                'callback' => [$this, 'list_cpt'],
                'permissions_callback' => [$this, 'permissions_callback']
            ], 
        );

        register_rest_route( 
            $this->namespace, 
            '/create-cpt', 
            [
                'methods' => 'POST',
                'callback' => [$this, 'create_new_cpt'],
                'permissions_callback' => [$this, 'permissions_callback']
            ], 
        );

        register_rest_route( 
            $this->namespace, 
            '/disable-cpt', 
            [
                'methods' => 'POST',
                'callback' => [$this, 'deactivate_cpt'],
                'permissions_callback' => [$this, 'permissions_callback']
            ], 
        );

    }

how can i call init The hook invokes my function and how do I enable or disable or remove the CPT when the admin page I’m creating a user from gives the corresponding command?

Leave a Comment