DevinVinson / WordPress-Plugin-Boilerplate

[WordPress] A foundation for WordPress Plugin Development that aims to provide a clear and consistent guide for building your plugins.
http://wppb.io
7.62k stars 2.25k forks source link

Rest api route not working with 'init' action. #550

Open bilalmalkoc opened 3 years ago

bilalmalkoc commented 3 years ago
public function create_custom_post_type() {
    $labels = array(...);

    $args = array(
        'label'               => esc_html__( 'Plugin', 'text-d' ),
        'description'         => '',
        'labels'              => $labels,
        'menu_icon'           => plugin_dir_url( dirname( __FILE__ ) ) . 'admin/img/menu-icon.png',
        'supports'            => array( 'title', 'thumbnail', 'author' ),
        'taxonomies'          => array(),
        'public'              => true,
        'show_ui'             => true,
        'show_in_menu'        => true,
        'menu_position'       => 5,
        'show_in_admin_bar'   => true,
        'show_in_nav_menus'   => false,
        'can_export'          => true,
        'has_archive'         => false,
        'hierarchical'        => false,
        'exclude_from_search' => true,
        'publicly_queryable'  => false,
        'capability_type'     => 'post',
        'show_in_rest'        => true,
        'rest_base'           => 'custom-plugin-api',
    );

    register_post_type( 'custom-plugin', $args );
}

define_admin_hooks: $this->loader->add_action( 'init', $plugin_admin, 'create_custom_post_type' );

With this snippet, rest-api returns this error: mysite.com/wp-json/wp/v2/custom-plugin-api

{
  "code": "rest_no_route",
  "message": "No route was found matching the URL and request method",
  "data": {
    "status": 404
  }
}

But it works if i put it directly in the main plugin file with basic init function.

codetot commented 3 years ago

I can guess a problem comes with this row:

'rest_base'           => 'custom-plugin-api',

While the environment is class-scoped, you should define something such as array($this, 'custom_plugin_api')