태그 보관물: wp-update-post

wp-update-post

save_post 작업에서 업데이트 및 새 게시물 확인 save_post 조치 내에서 새

save_post 조치 내에서 새 게시물이 작성되는지 또는 기존 게시물이 업데이트 중인지 판별 할 수 있습니까?



답변

WordPress 버전 3.7 이후. -IIRC- save_post후크 -Code Reference :save_postCodex :save_post 에서 후크 및 후크 사용법에 대한 자세한 정보 :$update이를 결정하는 데 사용할 수 있는 세 번째 매개 변수 가 있습니다.

@param int $ post_ID 게시물 ID.
@param WP_Post $ post 포스트 오브젝트.
@param bool $ update 업데이트중인 기존 게시물인지 여부입니다.


노트 :

$update항상 그런 것은 아닙니다 true. 아래 코드를 통해 직접 테스트하고 테스트 할 수 있습니다. 그러나 최적의 이름과는 거리가 멀기 때문에 잘 문서화되어 있지 않으므로 잘못된 예상을 만듭니다. 아래 코드는 일부 디버깅에 사용될 수 있습니다. 그렇지 않으면 정보 / 메시지가 표시되지 않기 때문에 코드 실행을 언제 가로 챌지를 사용해야합니다. 기만적인 행동의 원인은 수정 및 자동 저장을 처리하는 것입니다.이 기능은 비활성화 될 수 있지만 권장하지 않으며 테스트하지 않았습니다. 이것이 Trac Ticket을 보증하는지 확실 하지 않으므로 티켓을 열지 않았습니다. 그렇다고 생각되면 링크를 따라 직접하십시오. 그 외에도 의견에 명시된 바와 같이 특정 문제가 있으면 새로운 질문을 게시하십시오.

add_action( 'save_post', 'debug_save_post_update', 10, 3 );
function debug_save_post_update( $ID, $post, $update ) {

  echo '<pre>';
  print_r( $post ); echo '<br>';
  echo '$update == ';
  echo $update ? 'true' : 'false';

  //conditions
  if( ! $update && $post->post_status == "auto-draft" ) {
    // applies to new post
    echo ' && $post->post_status == "auto-draft"';
    //die();
  } else if ( ! $update ) {
    // applies basically to the (auto saved) revision 
    //die();
  } else {
    // applies to updating a published post
    // when there is a revision, which is normally the case, 
    // standard behavior of WordPress, then it is considered 
    // an update, which is where the confusion sets in
    // there are other methods, like checking time or post status
    // depending on your use case it might be more appropriate 
    // to use one of those alternatives 
    //die();
  }

  echo '</pre>';
  //die();
}


답변

이 확인을 수행하는 방법 (후크 기능 내)은 게시 날짜와 수정 날짜를 비교하는 것입니다 (표준화를 위해 GMT로).

function check_new_vs_update( $post_id ){
    $myPost        = get_post($post_id);
    $post_created  = new DateTime( $myPost->post_date_gmt );
    $post_modified = new DateTime( $myPost->post_modified_gmt );

    if( abs( $post_created->diff( $post_modified )->s ) <= 1 ){
        // New post
    }else{
        // Updated post
    }
}
add_action('save_post', 'check_new_vs_update' );

이는 생성시 게시물에 ‘수정 된’날짜가 첨부되어 있는데, 이는 ‘작성된’날짜와 정확히 동일하지만 생성하는 동안 두 번째가 똑딱 거리는 경우 1 초의 차이를 허용합니다. 게시물.


답변

설정하기 전에 사용자 정의 값이 있는지 확인했습니다. 그렇게하면 새로 작성된 게시물 인 경우 사용자 정의 값이 아직 존재하지 않습니다.

function attributes_save_postdata($post_id) {
  if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
  if (!wp_verify_nonce($_POST['_attributes_noncename'], plugin_basename(__FILE__))) return;
  if ('page' == $_POST['post_type']) {
    if (!current_user_can('edit_page', $post_id)) return;
  } else {
    if (!current_user_can('edit_post', $post_id)) return;
  }
  $termid = get_post_meta($post_id, '_termid', true);
  if ($termid != '') {
    // it's a new record
    $termid = 'update';
  } else {
    // it's an existing record
  }
  update_post_meta($post_id, '_termid', $termid);
}
add_action('save_post', 'attributes_save_postdata');


답변

“업데이트”파레 미터를 사용한 ialocin의 예 :

function save_func($ID, $post,$update) {

   if($update == false) {
     // do something if its first time publish
   } else {
     // Do something if its update
   }
}

add_action( 'save_post', 'save_func', 10, 3 );


답변

업데이트 코드에는 pre_post_update 작업 후크를 사용하고 새 포스트 코드에는 save_post를 사용할 수 있습니다. 게시물이 업데이트되기 전에 작동합니다.


답변

Darshan Thanki가 암시하고 (스티븐 해리스가 더 자세히 설명했듯이) pre_post_update이점을 활용할 수 있습니다 .

global $___new_post;
$___new_post = true;

add_action(
  'pre_post_update',
  function() {
    global $___new_post;
    $___new_post = false;
  },
  0
);

function is_new_post() {
  global $___new_post;
  return $___new_post;
}

내가 globals를 사용한 이유 function is_new_post() use ( &$new_post )는 PHP (shocking …)에서 유효하지 않기 때문에 해당 변수를 함수 범위로 가져 오는 것이 작동하지 않으므로 전역입니다.

이것은 save_post이벤트 내 / 후에 만 ​​실제로 안정적으로 사용될 수 있습니다 (적어도 우리가하는 일에 충분합니다).


답변

save_post가 트리거되면 해당 게시물에 대한 모든 정보가 이미 사용 가능하므로 이론적으로 사용할 수 있습니다.

function f4553265_check_post() {

    if (!get_posts($post_id)) {
    // if this is a new post get_posts($post_id) should return null
    } else {
    // $post_id already exists on the database
    }
}
add_action('save_post','f4553265_check_post');

그러나 이것은 테스트되지 않았습니다. =)