“TRANSPORT_POST_STATUS”操作使用wp_INSERT_POST创建两个POST

时间:2022-03-03 作者:Nayeem Farid

我最累的是,我已经创建了一个名为recipe的自定义帖子类型。在配方上创建新帖子时,我在另一个帖子类型上插入了一个新帖子。它工作正常,但在每个发布的帖子上都创建了两次帖子

    function post_create_on_publish_only( $new_status, $old_status, $post ) {

   if ( ( \'publish\' === $new_status )
       && \'recipe\' === $post->post_type
   ) {
      $my_post = array(
         \'post_title\'    => get_the_title($post),
         \'post_status\'   => \'publish\',
         \'post_type\' => \'wpcf7_contact_form\',
      );
      $get_post = get_page_by_title(get_the_title($post));
      if ( !is_page($get_post->ID) && did_action( \'transition_post_status\' ) === 1){
         $id = wp_insert_post( $my_post );
      }
   }
}
add_action( \'transition_post_status\', \'post_create_on_publish_only\', 10, 3 );

enter image description here

我如何解决这个问题?有人能帮我吗?

1 个回复
最合适的回答,由SO网友:tieum 整理而成

我记得在一个passed中有一个类似的问题,并检查是否有人首先发布了自定义帖子类型来为我解决这个问题,类似这样:

add_action( \'transition_post_status\', \'post_create_on_publish_only\', 10, 3 );
function post_create_on_publish_only( $new_status, $old_status, $post ) {

    if ( ( $new_status == \'publish\' ) && ( $old_status != \'publish\' ) && ( $post->post_type == \'recipe\' ) ) {
        $my_post = array(
            \'post_title\'    => get_the_title($post),
            \'post_status\'   => \'publish\',
            \'post_type\' => \'wpcf7_contact_form\',
        );
        $get_post = get_page_by_title(get_the_title($post));
        if ( !is_page($get_post->ID) && did_action( \'transition_post_status\' ) === 1){
            $id = wp_insert_post( $my_post );
        }
    } else {
        return;
    }
}

相关推荐