【问题标题】:Cannot create custom fields with the wpapi Node.js wrapper for WordPress REST无法使用 WordPress REST 的 wpapi Node.js 包装器创建自定义字段
【发布时间】:2019-12-09 18:11:31
【问题描述】:

我使用以下 sn-p 通过 REST API 使用 Node.js 包装器创建 WordPress 帖子:

   var wp = new WPAPI({
       endpoint: 'http://your-site.com/wp-json',
       username: 'someusername',
       password: 'password'
   });
   wp.posts().create({
       title: 'Your Post Title',
       content: 'Your post content',
       status: 'publish',
       meta: { "custom_field": "my custom field value" }
   }).then(function( response ) {
       console.log( response.id );
   })

获取帖子时,meta 为空。

为什么会这样,我该如何解决?

【问题讨论】:

    标签: javascript node.js wordpress rest api


    【解决方案1】:

    出于某种原因,这对我也不起作用。最后我使用了一个 WordPress REST 钩子。

    functions.php我加了:

    add_filter( 'pre_post_update' , function ( $post_id , $post ) {
      $body = json_decode(file_get_contents('php://input'), true);
      $meta_fields = $body["meta"];
      foreach ($meta_fields as $meta_key => $value) {
          update_post_meta($post_id, $meta_key, $value);
      }
    }, '99', 2 );
    

    上面的sn-p会解析meta字段,并更新post元数据字段。

    如果您想在响应中包含自定义字段,您可以使用:

    //Get custom fields via Rest API
    add_action( 'rest_pre_echo_response', function( $response, $object, $request ) {
      //* Get the post ID
      $post_id = $response[ 'id' ];
      if ($response['type'] !== 'post' && $response['type'] !== 'page') return $response;
      $response['custom_fields'] = get_post_meta($post_id);
      return $response;
    }, 10, 3 );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-05-14
      • 1970-01-01
      • 2017-10-29
      • 2020-09-01
      • 1970-01-01
      • 2013-11-25
      相关资源
      最近更新 更多