Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to properly set a value to meta fields of a custom post type? #359

Closed
jadealombro opened this issue Mar 20, 2018 · 2 comments
Closed

Comments

@jadealombro
Copy link

jadealombro commented Mar 20, 2018

I have a metafields that is assigned to a custom post which I added as a REST API field:

foreach( array( 'field_1', 'field_2' ) as $field ) {
    register_rest_field( $this->post_types,
     $field,
        array(
           'get_callback'    => array( $this, 'get_post_meta' ),
           'update_callback' => array( $this, 'update_post_meta' ),
           'schema'          => null,
         )
    ); 
}

And I also have the methods:

public function get_post_meta($object, $field_name, $request) {
    return get_post_meta( $object['id'], $field_name, true );
}

public function update_post_meta($value, $object, $field_name) {
    return update_post_meta( $object->ID, $field_name, $value );
}

If I test adding a new post/update and value to field_1 and field_2 through Postman, it works fine.

But when I try to add a value to the metafields, they don't seem to get added. Here is a snippet of the code I have:

response = await this.wordPress.cv_location().create({
      title: article.title,
      content: article.content,
      status: article.status,
      meta: {
        field_1: article.field_1,
        field_2: article.field_2,
      }
    });

I notice that if I use post() instead of cv_location(), the metafields get populated correcrtly with the values but the post gets added to the post post type and not the CV Location post type.

@kadamwhite
Copy link
Collaborator

Are you registering the meta using register_post_meta( 'your_cpt_name', [] ); on the PHP side? meta needs to be properly registered in order for the meta key to work. We need to add a better guide for this to the site, apologies for any confusion.

I know it's been a while but if you're using register_post_meta (introduced I believe in WP 4.9.8) and you're still seeing this issue, then please let us know. I'm going to leave it open as a documentation issue for now.

@kadamwhite
Copy link
Collaborator

Closing as a duplicate of #280 — I am be writing a meta handling guide to resolve that ticket which will give an example of this usage as well.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants