php – How to dynamically register custom post type

Question

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 is supposed to get all the needed params to create a new CPT. I’ve done a test but I’ve noticed that the CPT is not registered and I think it’s because I’m not calling the init hook. In my plugin code I’m creating four routes, one is to create new cpt, another to list all cpt and the last two will be used to enable or disable a 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 I can call the init hook insite my function and how I will enable or disable or delete CPT when from the admin page I’m creating the user will give the related command?

0
devdev 3 weeks 2022-11-05T15:31:57-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse