简体   繁体   中英

How to update woocommerce order number to a custom ACF field? (wordpress)

I have a custom post called "project", and it has an acf field called "ponum".

When a customer purchases a product, I'd like to add the customer's order number to the "ponum" field of the user's post in the custom post "project".

Getting an order number & creating a post works, but I have no idea how to add this number to the acf field on a thank you page.


add_action( 'woocommerce_thankyou', 'create_post_on_order' );

function create_post_on_order($order_id)
{
  global $wpdb;
  //print('<pre>'.print_r( $wpdb, true ).'</pre>');
  $order = wc_get_order($order_id);
  if (!$order->get_id()) {
    return;
  }

  $current_user = wp_get_current_user();
  $current_user_id = $current_user->display_name;
  $post_title = $order_id . ' - ' . $current_user_id;
  // Check post already exit with our title or not
  $query = $wpdb->prepare(
    'SELECT ID FROM ' . $wpdb->posts . '
      WHERE post_title = %s
      AND post_type = \'project\'',
    $post_title
  );
  $wpdb->query($query);

  if (!$wpdb->num_rows) {
    $post_id = wp_insert_post(
      array(
        'author'   => $current_user_id,
        'post_title'    => $post_title,
        'post_status'   => 'publish',
        'post_type'   => 'project'
      )
    );
  }     
}

Would you please help me?
Thank you.

Once you have the value for your acf (ie "$order_id"), then you could use the following code to update the acf field:

UPDATED ANSWER BASED ON YOUR NEW CODE

add_action('woocommerce_thankyou', 'create_post_on_order');

function create_post_on_order($order_id)
{
  $order = wc_get_order($order_id);
  if (!$order->get_id()) {
    return;
  }

  $current_user = get_userdata(get_current_user_id());
  $current_user_name = $current_user->display_name;
  $post_title = $order_id . ' - ' . $current_user_name;

  $query = new WP_Query(array(
    "author"    => get_current_user_id(),
    "post_type" => "project",
    "title"     => $post_title
  ));

  if ($query->found_posts == 0) {
    $post_id = wp_insert_post(
      array(
        'post_title'    => $post_title,
        'post_status'   => 'publish',
        'post_type'     => 'project',
        "meta_input"    => array(
          "ponum"       => $order_id
        )
      )
    );

    // It should work without this, this is just a double check!
    if (get_post_type($post_id) == "project") {

      $ponum_key = 'ponum';
      $ponum_field_value = get_field($ponum_key);

      if (empty($ponum_field_value)) {

        $ponum_field_value = $order_id;
        update_field($ponum_key, $ponum_field_value);
      }
    }
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM