Обновлено с 3.7.0 - реквизит @Baptiste для напоминания
3.7.0 представил хук "save_post_{$post->post_type}
", который будет запускаться типом записи. Это позволяет вам добавить действие, специфичное для вашего пользовательского типа записи (или «страницы» или «публикации» и т. Д.). Это сэкономит вам одну строчку из приведенных ниже.
Принятым методом является добавление действия к save_post_{post-type}
(в приведенном выше примере подстановка slug вашего типа сообщения вместо {post-type}
). Есть ряд проверок, которые вы можете / вероятно должны делать в обратном вызове вашего действия, что я документирую в следующем примере:
от Кодекса :
/* Register a hook to fire only when the "my-cpt-slug" post type is saved */
add_action( 'save_post_my-cpt-slug', 'myplugin_save_postdata', 10, 3 );
/* When a specific post type's post is saved, saves our custom data
* @param int $post_ID Post ID.
* @param WP_Post $post Post object.
* @param bool $update Whether this is an existing post being updated or not.
*/
function myplugin_save_postdata( $post_id, $post, $update ) {
// verify if this is an auto save routine.
// If it is our form has not been submitted, so we dont want to do anything
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return;
// verify this came from the our screen and with proper authorization,
// because save_post can be triggered at other times
if ( !wp_verify_nonce( $_POST['myplugin_noncename'], plugin_basename( __FILE__ ) ) )
return;
// Check permissions
if ( 'page' == $post->post_type )
{
if ( !current_user_can( 'edit_page', $post_id ) )
return;
}
else
{
if ( !current_user_can( 'edit_post', $post_id ) )
return;
}
// OK, we're authenticated: we need to find and save the data
$mydata = $_POST['myplugin_new_field'];
// Do something with $mydata
// probably using add_post_meta(), update_post_meta(), or
// a custom table (see Further Reading section below)
return $mydata;
}
Если вы регистрируете несколько пользовательских типов записей и хотите объединить функциональность save_post в одну функцию, подключите универсальное действие save_post
. Но затем не забудьте выполнить проверку типов записей в своей функции, если есть какие-либо различия в том, как эти типы записей сохраняют свои данные.
Например: if ( 'my-cpt-1' == $post->post_type ){ // handle my-cpt-1 specific stuff here ...