我正在尝试编写一个插件,如果某个给定的条件不满足,我将阻止用户发布(或更新)一篇文章,例如,如果该文章的标题已经在另一篇文章中使用(我正在使用自定义的文章类型,如果这样做会产生影响的话)。我编写了一个函数,通过“transition\\u post\\u status”钩子调用该函数,试图在日志在数据库中发布或更新之前捕获该日志,以便阻止这种情况的发生。当我用一个我知道已经使用过的标题进行测试时,当wp\\u die()函数发生时,我会看到错误消息,所以我知道这个函数正在被调用。然而,无论如何,这篇文章正在创建中。我有什么遗漏吗?这是在将帖子保存到数据库之前检查条件的最佳方法吗?
这是我在构造器中拥有的:
add_action( \'transition_post_status\', array( $this, \'post_publish_control\' ), 10, 3 );
课程后期:public function post_publish_control( $new_status, $old_status, $post ) {
// Make sure this function runs on correct post type
if( $post->post_type === \'my_custom_post_type\' ) {
// On first-time publish or post update
if( $new_status === \'publish\' ) {
// Try to catch an already existing title before post is saved
if( does_post_title_exist( $post->post_title ) ) {
wp_die( \'Title is already being used, try a different one.\' );
}
// Continue if conditions are met
else {
return;
}
}
}
}
我更习惯于面向对象编程,所以我尝试将这个插件作为自己的类来编写。