我试图结合我的两个功能,但我无法弄清楚如何。我想要特色图片。我知道有很多类似的问题,但它们始终以wp_die();
结尾,在我看来并不是真的用户友好。我无法解决Wordpress错误信息。
我的代码应该做什么:
PS:目前,在打开或创建帖子时会立即显示错误消息。它应该不是那样的。
我目前的代码是:
function featured_image_required($post_id, $post, $update){
$post_type = $post->post_type;
$id = $post_id;
if(!has_post_thumbnail($id) AND $post_type == "custom_post_type") {
remove_action('save_post', 'featured_image_required');
$query = array(
'ID' => $id,
'post_status' => 'draft',
);
wp_update_post($query, true);
add_action('save_post', 'featured_image_required');
}
}
add_action('save_post', 'featured_image_required', 10, 3 );
function show_editor_message($messages){
global $post;
$post_type = $post->post_type;
if (!has_post_thumbnail($post_id) AND $post_type == "custom_post_type") {
$error_message = 'Featured Image is required! The post was not published.';
add_settings_error('featured_image_required', '', $error_message, 'error');
settings_errors( 'featured_image_required' );
return;
}
return $messages;
}
add_action('post_updated_messages', 'show_editor_message');
答案 0 :(得分:1)
一个选项就是测试帖子的初始状态(此处为自动草稿'),如果帖子处于该状态,则不显示消息。
save_post
操作需要对状态进行额外检查,否则,如果帖子没有精选图片(例如,无法删除帖子),则该帖子将始终返回到草稿状态
以下是修改过的代码:
function featured_image_required($post_id, $post, $update){
$post_type = $post->post_type;
$id = $post_id;
if($post->post_status == "publish" AND !has_post_thumbnail($id) AND $post_type == "custom_post_type") {
remove_action('save_post', 'featured_image_required');
$query = array(
'ID' => $id,
'post_status' => 'draft',
);
wp_update_post($query, true);
add_action('save_post', 'featured_image_required');
}
}
add_action('save_post', 'featured_image_required', 10, 3 );
function show_editor_message($messages){
global $post;
$post_type = $post->post_type;
if ($post->post_status != "auto-draft" AND !has_post_thumbnail($post->ID) AND $post_type == "custom_post_type") {
$error_message = 'Featured Image is required! The post was not published.';
add_settings_error('featured_image_required', '', $error_message, 'error');
settings_errors( 'featured_image_required' );
return;
}
return $messages;
}
add_action('post_updated_messages', 'show_editor_message');