D
D
Danil Klimov2021-07-25 21:02:43
WordPress
Danil Klimov, 2021-07-25 21:02:43

How to add an ID to the post name when creating it?

When a person fills out a form on the site and submits it, an order is created. And the post is added to the admin panel, thus:

$post_data = [
    'post_title'        => 'Новый заказ',
    'post_status'	=> 'pending',
    'post_author'	=> 1,
    'post_type'		=> 'mail',
  ];
$post_ID = wp_insert_post( $post_data );

And then a number of metafields are added.
I want the post name to be "New Order # {Post ID}".
Of course, I can do it again after the above code wp_insert_post()and change the name. But it seems to me that there should be a better solution.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
Y
yarovikov, 2021-07-26
@Madgod

Everything is simple. Also does woocommerce:

$purchase_information = array(
  'post_title' => '',
  // ...
);						

$purchase = wp_insert_post( $purchase_information );
$my_purchase = array();
$my_purchase['ID'] = $purchase;
$my_purchase['post_title'] = __( 'Покупка №' ) . ' ' . $purchase;
wp_update_post( wp_slash( $my_purchase ) );

A
Alex, 2021-07-25
@Kozack

The post ID is generated after the post itself has been added to the database. In other words, until you create a post, it simply doesn't have an ID. So putting an ID in the title can only be done in two steps: create a post and then update its title

A
Artem Zolin, 2021-07-25
@artzolin

I can offer you a crutch solution in the form of the_title filter, like this

add_filter( 'the_title', 'add_event_time_in_the_title', 10, 2 );
function add_event_time_in_the_title( $title, $post_id ) {

  // добавляем время проведения мероприятий после заголовка
  if ( get_post_type() === 'event' ) {
    $event_time = get_post_meta( get_the_ID(), '_event_time', true );
    $title = $title . ' ' . $event_time;
  }

  return $title;
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question