wordpress中wp_rest_api应用

现在在做一个前后端分离的消息类网站,通过wx_rest_api来做数据交互。


技术栈:nuxt+wordpress。


现在有一个问题,在wordpress后台自定义页面,通过写菜单栏跳转到用javascript写的页面,通过axios,rest_api来传表单数据,请问在数据库中自己新建表,通过rest_api来访问吗?


图片说明


如下,用的都是已经定义好的,posts来储存文章。


this.$axios
    .get("posts?categories=21&_embed")
    .then(res => { })
    .catch(err => {
      console.error(err);
    });


我想新建products,来存储其他的分类,比如产品,但不是存在posts当中。这样可以实现吗?

您可以通过自定义插件或使用现有的插件来创建新的自定义表,并使用wp_rest_api来访问它们。对于自定义表的创建,您可以参考WordPress官方文档上的指导。然后,您可以使用custom endpoints或者自定义api endpoints的方式来实现对自定义表的访问。例如,

function register_custom_route() {
    register_rest_route( 'my/v1', '/products', array(
        'methods' => 'POST',
        'callback' => 'create_new_product',
    ));
}
add_action( 'rest_api_init', 'register_custom_route' );

function create_new_product( $data ) {  
    // insert logic to create new product in custom table
}

这个示例注册了一个自定义的rest api路由来创建新的产品,并提供了适当的逻辑来在自定义表中插入产品数据。您可以在您的WordPress自定义的插件中包含这段代码。然后,您的axios请求可以像下面这样向新的自定义路由发送一个POST请求:

this.$axios
    .post("my/v1/products", { /* product data here */ })
    .then(res => { })
    .catch(err => { console.error(err); });

这将触发create_new_product回调,该回调将创建一个新的产品并将它保存到自定义表中。