Files
thalim-theme/inc/post-title-required.php
2026-05-12 23:33:46 +02:00

58 lines
1.9 KiB
PHP

<?php
/**
* Require a non-empty title when saving a post from the admin.
*
* Uses the same transient / redirect / restore mechanism as pods-save-error-handler.php
* so content is never lost: the post saves (with empty title), the status is reverted
* to draft if needed, the editor reopens with all fields restored and an error notice.
*/
add_action( 'save_post', 'thalim_check_post_title_required', 5 );
function thalim_check_post_title_required( $post_id ) {
if ( wp_is_post_autosave( $post_id ) || wp_is_post_revision( $post_id ) ) {
return;
}
if ( ! is_admin() ) {
return;
}
if ( ( $_POST['action'] ?? '' ) !== 'editpost' ) {
return;
}
$post = get_post( $post_id );
if ( ! $post || ! post_type_supports( $post->post_type, 'title' ) ) {
return;
}
// Title was provided — nothing to do.
if ( trim( wp_unslash( $_POST['post_title'] ?? '' ) ) !== '' ) {
return;
}
// Title is empty: store restore transient and signal the redirect handler
// (same keys as pods-save-error-handler.php so everything is shared).
$user_id = get_current_user_id();
$restore = [];
foreach ( $_POST as $key => $val ) {
if ( str_starts_with( $key, 'pods_meta_' ) ) {
$restore[ $key ] = is_array( $val )
? array_map( 'wp_unslash', $val )
: wp_unslash( $val );
}
}
$restore['_msg'] = __( 'Le champ Titre est obligatoire.', 'thalim' );
$restore['_title'] = ''; // intentionally empty — user must fill it
set_transient(
'thalim_pods_restore_' . $post_id . '_' . $user_id,
$restore,
10 * MINUTE_IN_SECONDS
);
// Signal redirect_post_location (defined in pods-save-error-handler.php):
// it will revert the post status if needed and redirect to the edit screen.
$GLOBALS['thalim_pods_error_post_id'] = $post_id;
}