【问题标题】:Wordpress REST API EndpointWordpress REST API 端点
【发布时间】:2016-04-20 04:10:00
【问题描述】:

我正在编写一个 Angular WP 主题,并试图减少帖子页面上的 HTTP 请求数量。

在帖子页面上,我想列出所有不同的分类法、最近的帖子、获取特色图片和其他一些内容。我可以通过 REST API v2 插件的单个请求来完成这一切,但这是很多请求。

我希望为我的主题创建一个端点,解析 post slug 并在一个请求中将其全部取回,但我似乎无法弄清楚。

我正在考虑使用查询字符串来获取 slug。这是我一直用来测试的:

function app_get_post($data) {
    global $wp_query;

    return [
        'test' => $data,
        'vars' => $wp_query->query_vars
    ];
}

add_action( 'rest_api_init', function () {
    register_rest_route( 'app/v1', '/post', [
        'methods' => 'GET',
        'callback' => 'app_get_post',
    ] );
} );

这是它产生的结果:

{
test: { },
vars: [ ]
}

我确实尝试使用query_vars 钩子添加查询变量,但它也不起作用。

有什么建议吗?我这样做是否正确?

【问题讨论】:

    标签: php angularjs wordpress rest


    【解决方案1】:

    你应该传递参数

    function app_get_post($data) {
    
        return [
            'test' => $data["postid"]        
        ];
    }
    
    add_action( 'rest_api_init', function () {
        register_rest_route( 'app/v1', '/post/(?P<postid>\d+)', [
            'methods' => 'GET',
            'callback' => 'app_get_post',
        ] );
    } )
    

    例如参考http://wiki.workassis.com/wordpress-create-rest-api/

    【讨论】:

      【解决方案2】:

      所以我也在学习这一切,还没有成功,但会提供我的研究点。我知道要使用自定义帖子类型,您需要将 show_in_rest=true 添加到 register_post_type() 数组或稍后再加入它。

      但是,您的示例显示了帖子的使用,我猜它应该在注册位置 show_in_rest... 我决定检查 wp-includes/post.php 并且它不存在。

      // ACCESSING A CPT FROM ANYWHERE (unable to add show_in_rest=true to the register_post_type() hook into it!)
      // http://scottbolinger.com/custom-post-types-wp-api-v2/
      function sb_add_cpts_to_api( $args, $post_type ) {
          if ( 'movie' === $post_type ) {
              $args['show_in_rest'] = true;
              $args['rest_base'] = 'movie';
              // $args['rest_controller_class'] = 'WP_REST_Posts_Controller';
          }
          return $args;
      }
      add_filter( 'register_post_type_args', 'sb_add_cpts_to_api', 10, 2 );
      

      【讨论】:

        【解决方案3】:

        这里你需要传递如下所示的参数

        //端点:http://wpdadd.com/wp-json/api/v1/getwp/{parameter 1}/{parameter2}

        register_rest_route( 'api', '/v1/getwp/(?P<param1>[a-z0-9\-]+)/(?P<param2>[a-z0-9\-]+)', array(
            'methods' => 'GET',
            'callback' => 'wpdaddStuff'
        
        ));
        

        有关更多信息,您可以在此处查看此示例http://wpdadd.com/create-custom-rest-api-wordpress/

        【讨论】:

          猜你喜欢
          • 2018-05-14
          • 1970-01-01
          • 2020-07-23
          • 2022-10-21
          • 1970-01-01
          • 2019-04-07
          • 2017-01-14
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多