skip to Main Content

What I’m working in: WordPress with ACF plugin and JavaScript.

What I’m trying to do: create a post and set the title, content, status and some ACF-fields.

What is output: It successfully creates the post, but only sets the title and content. The ACF-fields are blank.

What alternatives I have tried: tried changing ‘acf_fields:’ to ‘fields:’ with no luck.

Question: Am I using the wrong label for ACF-fields? Or is there another way of doing this?

  createMarker(latitude, longitude) {
    var ourNewPost = {
      title: latitude + ", " + longitude,
      content: "Coordinates: " + latitude + ", " + longitude,
      status: "publish",
      acf_fields: {
        points_title: "test",
        points_latitude: latitude.toString(),
        points_longitude: longitude.toString(),
        status: 0
      },
    };

    $.ajax({
      beforeSend: (xhr) => {
        xhr.setRequestHeader("X-WP-Nonce", myData.nonce);
      },
      url: myData.root_url + "/wp-json/wp/v2/points/",
      type: "POST",
      data: ourNewPost,
      success: (response) => {
        console.log(response);
      },
      error: (response) => {
        console.log(response);
      },
    });
  }

Defining my custom post-type:

function points(){
  register_post_type('points', array(
    'show_in_rest' => true,
    'map_meta_cap' => true,
    'supports' => array('title', 'editor','custom-fields'),
    'show_ui' => true,

    'public' => true,
    'labels' => array(
      'name' => 'Points'
    )
  ));

}
add_action('init', 'points');

2

Answers


  1. You have to call hook when post save and then you can write your code in hook to fill acf field data.

    add_action('acf/save_post', 'set_acf_data');
    
    function set_acf_data($post_id)
    {
      
      $acf_data= "Your Data which you want to add in ACF field";
    
      if ('post' == get_post_type($post_id)) {
    
        update_field('acf_key', $acf_data, $post_id);
    
      }
    }
    
    Login or Signup to reply.
  2. The problem is in your CreateMarker function. The object field key for the ACF fields is incorrect – it should simply be: acf

    createMarker(latitude, longitude) {
        var ourNewPost = {
          title: latitude + ", " + longitude,
          content: "Coordinates: " + latitude + ", " + longitude,
          status: "publish",
          acf: {
            points_title: "test",
            points_latitude: latitude.toString(),
            points_longitude: longitude.toString(),
            status: 0
          },
        };
    

    Here’s the documentation link which shows the entire POST fields.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search