Post statuses update php

wp_transition_post_status() │ WP 2.3.0

Запускает хуки (события) для любых изменений статусов записей (с draft на publish , с publish на private и т.д.). Эта функция вызывается в ядре WordPress из других функций, чтобы уведомить плагины, темы и функции ядра о смене статуса записи. А точнее, её ВСЕГДА вызывают wp_update_post(), wp_insert_post() и wp_publish_post().

wp_insert_post() вызывает этот хук всегда, когда создается или обновляется запись любого типа (кроме attachment).

Эта функция не меняет статус поста, она только вызывает хуки. Для реальной смены статуса поста, нужно обновить данные поста с помощью соответствующих функций: wp_update_post() или wp_publish_post(). Хуки, которые вызывает эта функция: transition_post_status Используйте когда нужно подключиться при любом изменении статуса.

do_action( 'transition_post_status', $new_status, $old_status, $post );

(old_status)_to_(new_status) Используйте когда нужно подключиться при конкретных изменениях статуса (с одного на другой).

  • new_to_publish — при первой публикации новой записи, например если запись добавляется функцией wp_insert_post() .
  • auto-draft_to_publish — при первой публикации новой записи из админки WP.
  • draft_to_publish — при публикации, сохраненной записи.
  • future_to_publish — при публикации запланированной записи.

Используйте когда нужно сделать что-либо для указанного статуса и типа поста.

do_action( "_post_type>", $post->ID, $post );

Несколько полезных вариантов хука:

  • publish_post — Позволяет сделать что-либо, когда пост (запись типа post) публикуется или обновляется. Срабатывает всегда когда создается/обновляется пост со статусом publish . Поэтому, если нужно делать что-либо один раз, только когда пост публикуется (а не обновляется), используйте хуки выше.
  • pending_post — срабатывает всякий раз когда создается/обновляется пост со статусом pending .
  • draft_post — срабатывает всякий раз когда создается/обновляется черновик — пост со статусом draft .
Список всех статусов, которые могут применяться в хуках:
  • new — если еще не было установленных никаких статусов.
  • publish — опубликованный пост (страница или тип записи).
  • pending — запись на рассмотрении перед публикацией.
  • draft — черновик записи.
  • auto-draft — только созданный пост, еще без заголовка, контента и другой информации.
  • future — запись запланированная к публикации в будущем.
  • private — запись не доступная не авторизованным пользователям.
  • inherit — ревизия или вложение (revision or attachment). Смотрите get_children().
  • trash — запись находящаяся в корзине.
Хуки из функции

Возвращает

null . Ничего не возвращает.

Использование

wp_transition_post_status( $new_status, $old_status, $post );

$new_status(строка) (обязательный) Какой статус поста будет. $old_status(строка) (обязательный) Какой статус поста был. $post(WP_Post) (обязательный) Данные поста. Объект.

Примеры

#1 Посмотрим как работает функция

Для этого давайте взглянем на код функции wp_publish_post():

function wp_publish_post( $post ) < global $wpdb; if ( ! $post = get_post( $post ) ) return; if ( 'publish' == $post->post_status ) return; $wpdb->update( $wpdb->posts, array( 'post_status' => 'publish' ), array( 'ID' => $post->ID ) ); clean_post_cache( $post->ID ); $old_status = $post->post_status; $post->post_status = 'publish'; // теперь, когда статус поста изменен, вызываем хуки, // к которым в последствии смогут подключится плагины, темы и другие функции. wp_transition_post_status( 'publish', $old_status, $post ); do_action( 'edit_post', $post->ID, $post ); do_action( "save_post_post_type>", $post->ID, $post, true ); do_action( 'save_post', $post->ID, $post, true ); do_action( 'wp_insert_post', $post->ID, $post, true ); >

#2 Использование хука _to_

Читайте также:  Bank application in java

Добавим действие, которое будет срабатывать при изменении статуса draft на publish — draft_to_publish , т.е. при публикации черновика.

add_action( 'draft_to_publish', function( $post ) < // ваш код >);

Если нужно подключится к моменту одобрения (pending) поста, то нужно использовать хук pending_to_publish .

#3 Использование хука transition_post_status

Это общий хук, срабатывает когда нам нужно подключиться в момент смены любого статуса на любой. Хук передает 3 параметра: $new_status, $old_status, $post.

Этот пример показывает как подключаться, когда статус поста меняется с publish на любой другой статус:

add_action( 'transition_post_status', 'post_unpublished', 10, 3 ); function post_unpublished( $new_status, $old_status, $post ) < if ( $old_status == 'publish' && $new_status != 'publish' ) < // Пост снят с публикации >>

#4 Хук, срабатывающий при любой смене статуса

add_action( 'transition_post_status', 'intercept_all_status_changes', 10, 3 ); function intercept_all_status_changes( $new_status, $old_status, $post ) < if ( $new_status != $old_status ) < // Статус поста изменен >>

#5 Использование хука _post_type>

Если нужно подключиться к текущему статусу, независимо от того какой был статус до этого используем конструкцию: СТАТУС_ТИПЗАПИСИ .

Например, если нужно что-то сделать когда пост со статусом publish публикуется или обновляется, то конструкция будет выглядеть так publish_post :

add_action( 'publish_post', 'publish_post_action', 10, 2 ); function publish_post_action( $post_id, $post )< // делаем что-то при публикации поста >

Обратите внимание, что этот хук будет срабатывать и при обновлении записи, если при обновлении статус указан publish или если статус не был указан, но при этом до этого он был publish .

Список изменений

Код wp_transition_post_status() wp transition post status WP 6.2.2

function wp_transition_post_status( $new_status, $old_status, $post ) < /** * Fires when a post is transitioned from one status to another. * * @since 2.3.0 * * @param string $new_status New post status. * @param string $old_status Old post status. * @param WP_Post $post Post object. */ do_action( 'transition_post_status', $new_status, $old_status, $post ); /** * Fires when a post is transitioned from one status to another. * * The dynamic portions of the hook name, `$new_status` and `$old_status`, * refer to the old and new post statuses, respectively. * * Possible hook names include: * * - `draft_to_publish` * - `publish_to_trash` * - `pending_to_draft` * * @since 2.3.0 * * @param WP_Post $post Post object. */ do_action( "_to_", $post ); /** * Fires when a post is transitioned from one status to another. * * The dynamic portions of the hook name, `$new_status` and `$post->post_type`, * refer to the new post status and post type, respectively. * * Possible hook names include: * * - `draft_post` * - `future_post` * - `pending_post` * - `private_post` * - `publish_post` * - `trash_post` * - `draft_page` * - `future_page` * - `pending_page` * - `private_page` * - `publish_page` * - `trash_page` * - `publish_attachment` * - `trash_attachment` * * Please note: When this action is hooked using a particular post status (like * 'publish', as `publish_post_type>`), it will fire both when a post is * first transitioned to that status from something else, as well as upon * subsequent post updates (old and new status are both the same). * * Therefore, if you are looking to only fire a callback when a post is first * transitioned to a status, use the hook instead. * * @since 2.3.0 * @since 5.9.0 Added `$old_status` parameter. * * @param int $post_id Post ID. * @param WP_Post $post Post object. * @param string $old_status Old post status. */ do_action( "_post_type>", $post->ID, $post, $old_status ); >

Cвязанные функции

statuses (статус записи коммента юзера)

Остальное

  • comments_open()
  • get_extended()
  • get_lastpostdate()
  • get_lastpostmodified()
  • get_post_embed_html()
  • get_post_embed_url()
  • get_post_parent()
  • get_post_timestamp()
  • has_post_parent()
  • is_sticky()
  • pings_open()
  • post_exists()
  • sanitize_post()
  • the_shortlink()
  • url_to_postid()
  • wp_embed_register_handler()
  • WP_Embed::delete_oembed_caches()
  • wp_get_canonical_url()
  • wp_get_shortlink()
  • wp_oembed_add_provider()
Читайте также:  Css global background color

Источник

Maintaining a Post Status When Updating a WordPress Post

I just finished a feature for a project that uses a combination of custom post types, data imports, and updating existing posts when deleting a user (or set of users).

There’s one problem, though:

Say have you have a post that’s currently published (that is, it’s ‘post_status’ is set to ‘publish’) but, when you update the post via wp_update_post, its post_status attribute is set to ‘future.’

In order words, whenever you programmatically update a post, the status of the post is set to ‘Scheduled’ (according to the UI) and ‘future’ (according to the database column).

Post Status When Updating

Generally speaking, I’m not a fan of getting something to work, finding out that it does, and moving on to the next task unless I understand exactly why it didn’t work [as expected] in the first place.

This isn’t to say that there aren’t times where constraints have caused this to happen (at least during working hours). But if it’s midnight, I fix a bug, and then I’m not totally sure I understand why it was apparently broken in the first place, I might as well stay up and figure it out right?

It’s like the programmer’s version of sunk cost bias.

Anyway, as outlined above, here’s the gist of the problem:

  1. A given post exists in WordPress.
  2. When a user is deleted, the system looks to see if certain content exists within a given post and, if so, removes it.
  3. The post is then updated using a WordPress API function.

Everything works great except there’s a problem: Whenever the post is programmatically updated, it marks the post’s status as ‘future’ in the database ultimately setting the post’s line item in the All Posts view as “Scheduled.”

Two Solutions

There are two ways to fix this problem:

  1. Run a quick query directly against the database to fix the problem.
  2. Update the post’s arguments to use the proper time in GMT (I’ll cover this more in a moment).

If you opt for the first solution, then make sure you use the prepare function and make sure you execute the query after the update function is returned.

If you opt for the second solution, then explicitly update the properties of the post object before passing it to the update function.

Читайте также:  Python call method by string

I’m not one to say there isn’t a place for either of these solutions when working on a project, but the question remains:

Why is WordPress marking a post scheduled for the future when the post, before going through the update procedure, was set to publish?

And if you’re not familiar with the rest of the arguments that are passed to WordPress when updating a post, it will take some time to track it down.

Understanding The Problem

For the sake of avoiding writing a direct database query, I opt to go with the second solution because it’s cleaner (though it doesn’t make it any less confusing).

To figure out why this behavior happens, you can ask another developer or debug the code. Given that I was working on this late at night, I opted for the latter.

Post Status When Updating: Tracing Code in post.php

Running the debugger and tracing code through post.php.

I’m not going to talk through all of the breakpoints and watches that I set, so I’ll try to make this as concise as possible.

First, when the code runs through the wp_update_post function it will encounter this block of code:

Notice that within the conditional, we’re not working with an attachment and we’re working with a post status of ‘publish.’ So we’re going to hit the first conditional within the outer conditional (a bit confusing isn’t it?).

Now there’s a variable, $post_status, maintaining a value of publish but it’s not assigned to any particular property of the current post. If you continue tracing the code, you’ll come across the next line:

Here, you’ll see that it’s working with a set of array keys that are contained in the $postarr variable. This variable is used earlier in the code (see it here on Trac). And if you look closely, you’ll see that it first checks to see if the post_date_gmt property is empty or if its all zeroed out.

And since it’s not, it will use the value that we specified on the property when we initially called the function:

Why go back up into the function when the code has already run past this? That’s the nature of debugging. Sometimes you see variables and don’t think anything of them only to see they are used, set, manipulated, combined, or whatever else later in the code.

But anyway, because of that, the property will maintain the value that we supplied before calling the update function. Usually, this will be the same value as when the function started, but there may be times where you want to, say, trash a post.

And that’s grounds for using wp_delete_post. But it has its caveats, too especially around custom post types.

That gets into another post, though.

Leave a Reply Cancel reply

You must be logged in to post a comment.

Источник

Оцените статью