自定义API终结点WordPress上的REST_NO_ROUTE

时间:2018-03-06 作者:GeneralCan

我在最后一天左右一直想弄明白这一点,但没有结果。

我试图创建一个端点来从一组表中收集数据。我正在尝试用面向对象的语言编写它,因为我需要学习。

这是我的课:

         class b2_items_rest_route extends WP_REST_Controller{
         private $wpdb;

         public function __construct(){
             global $wpdb;
             $this->wpdb = $wpdb;
         }

         public function b2_register_route(){
             $version = \'1\';
             $namespace = \'b2rest/v\' . $version;
             $base = \'route\';

             register_rest_route( $namespace, \'/\' . $base,
                array(
                    array(
                        \'methods\'             => WP_REST_Server::READABLE,
                        \'callback\'            => array($this, \'items_by_id\'),
                        \'permission_callback\' => array($this, \'get_items_permissions_check\' ),
                        \'args\'                => array(),
                    ),
                )
            );

            register_rest_route( $namespace, \'/\' . $base . \'/trees/(?P<id>[\\d]+)\',
                array(
                    array(
                        \'methods\'             => WP_REST_Server::READABLE,
                        \'callback\'            => array($this, \'items_by_id\'),
                        \'permission_callback\' => array($this, \'get_item_permissions_check\' ),
                        \'args\'                => array(),
                    )
                )
            );
         }

         function items_by_id($request){
             global $wpdb;
             //$tree_id = $request->get_param(\'id\');
             $tree = $wpdb->get_results("SELECT * FROM bb_bower__tree_configuration WHERE tree_id=47");
         }

         public function get_items_permissions_check($request){
             return true; // make endpoint available for everyone to read.
         }

     }

     $b2_items_rest_route = new b2_items_rest_route;
     add_action(\'rest_api_init\', $b2_items_rest_route->b2_register_route);
问题是我在《邮递员》中不断得到rest\\u no\\u路线,但当我定期重写它时,效果很好。

如有任何指示,将不胜感激,谢谢!

1 个回复
最合适的回答,由SO网友:Tom J Nowell 整理而成

这无效:

add_action(\'rest_api_init\', $b2_items_rest_route->b2_register_route);
当然,这应该会生成警告或致命错误

add_action 将PHP可调用作为第二个参数,例如:

  • \'function_name\'
  • function( $im_a_closure_yay) {}
  • array( \'class_name\', \'static_method\' )
  • array( $object, \'method\' )

结束