发布所有自定义帖子类型时,没有一个钩子会触发。但是我们可以使用挂钩和条件的组合来完成同样的事情。除了另一个答案外,至少有两种方法可以做到这一点。第一个是钩住register_post_type 并有条件地向publish_$post_type 如果帖子类型不是WordPress默认值。下面是一个插件示例。
namespace = StackExchange\\WordPress;
class plugin {
  protected $defaultPostTypes = [
    \'post\', \'page\', \'attachment\', \'revision\',
    \'nav_menu_item\', \'custom_css\', \'customize_changeset\',
  ];
  public function plugins_loaded() {
    \\add_action( \'registered_post_type\', [ $this, \'registered_post_type\' ], 10, 2 );
  }
  public function registered_post_type( string $post_type, \\WP_Post_Type $post_type_object ) {
    if( in_array( $post_type, $this->defaultPostTypes ) ) return;
    \\add_action( "publish_$post_type", [ $this, \'publish_post_type\' ], 10, 3 );
  }
  public function publish_post_type( int $post_ID, \\WP_Post $post, bool $update ) {
    //* This method will execute whenever a custom post type is published.
  }
}
\\add_action( \'plugins_loaded\', [ new plugin(), \'plugins_loaded\' ] );
 或者,我们可以使用
transition_post_status 钩
function wpse_135423_transition_post_status( $new_status, $old_status, $post ) {
  //* Make sure the new status is published
  if( \'publish\' !== $new_status ) return;
  //* And that the post_type isn\'t one of the WordPress defaults
  $default = array(
    \'post\', 
    \'page\', 
    \'attachment\', 
    \'revision\',
    \'nav_menu_item\', 
    \'custom_css\', 
    \'customize_changeset\',
  );
  if( in_array( $post->post_type, $default ) ) return;
  //* A custom post type just got published.
}
add_action( \'transition_post_status\', \'wpse_135423_transition_post_status\', 10, 3 );