programing

모든 포스트 데이터와 포스트 메타를 저장한 후 발생하는 WordPress 훅은 무엇입니까?

golfzon 2023. 3. 20. 23:47
반응형

모든 포스트 데이터와 포스트 메타를 저장한 후 발생하는 WordPress 훅은 무엇입니까?

커스텀 포스트 타입의 crm이 있으며, crm이 저장 또는 갱신될 때마다 메일을 보내야 합니다.i 사용자 cmb2는 사용자 정의 메타와 유사한 서브젝트, 사용자 등에 대한 것입니다.나는 알고 있다save_post(WordPress codex에 따르면) 저장 후 후 후크 발생을 호출할 때save_post2개의 파라미터(id와 post)가 있는 게시물에는 업데이트 값이 포함되어 있지 않습니다.코드는 다음과 같습니다.

function send_mail_to_user($id, $post){
    $crm = $post;
    $user_email = array();
    if($crm->vc_all_vc == 'on'){
        $args = array('orderby' => 'display_name');
        $wp_user_query = new WP_User_Query($args);
        $authors = $wp_user_query->get_results();
        if (!empty($authors)) {
            foreach ($authors as $author) {
                array_push($user_email , $author->user_email );
            }
        } 
    }
    else{
        $to_users = $crm->vc_users;
        $to_program = $crm->vc_program;
        $to_group = $crm->vc_group;
        $to_excode = $crm->vc_ex_code;
        foreach ($to_users as $key => $value) {
            $user_data = get_userdata($value);
            array_push($user_email, $user_data->user_email);
        }
        foreach ($to_program as $key => $value) {
            $users = get_users( array('meta_key'     => 'programs'  ) );
            if($users){ 
                foreach ($users as $index => $data) {
                    if(in_array($value , explode('#', $data->programs))){
                        if(! in_array($data->user_email, $user_email)  )
                        {
                            array_push($user_email, $data->user_email);
                        }
                    }
                }
            }
        }
        foreach($to_group as $group) {
            $term = get_term_by('slug', esc_attr($group), 'user-group');
            $user_ids = get_objects_in_term($term->term_id, 'user-group');
            foreach($user_ids as $user_id){
                $fc_user = get_userdata($user_id);
                if(! in_array($fc_user->user_email, $user_email)  )
                {
                    array_push($user_email, $fc_user->user_email);
                }
            }   
        }
        foreach($to_excode as $codes) {
            $value = explode('*',$codes)[1];
            $users = get_users( array('meta_key'     => 'programs'  ) );
            if($users){ 
                foreach ($users as $index => $data) {
                    if(in_array($value , explode('#', $data->programs))){
                        if(! in_array($data->user_email, $user_email)  )
                        {
                            array_push($user_email, $data->user_email);
                        }
                    }
                }
            }   
        }
    }
    foreach($user_email as $index => $email){
        $to      = $email;
        $subject = $crm->vc_subject;
        $body    = $crm->post_content;
        $headers = array(
        'Content-Type: text/html; charset=UTF-8'
        );
        wp_mail($to, $subject, $body, $headers);
    }
}

add_action( 'save_post', 'send_mail_to_user', 10, 2 ); 

그리고 나도 노력한다.publish_post후크: 새로운 투고가 작성되었을 때는 정상적으로 동작하지만 갱신되었을 때는 동일하게 동작합니다.난 시도했다.edit_post그리고.post_updated후크도 있지만 업데이트 데이터를 가져올 수 없습니다.

그럼 어떻게 해결할까요?어떤 액션 훅이 모든 새로운 데이터를 제공합니까?잘 부탁드립니다.

이런 거 써도 되는데

function your_custom_function($meta_id, $post_id, $meta_key='', $meta_value='') {
    if($meta_key=='_edit_lock') {
        // if post meta is updated
    }
}
add_action('updated_post_meta', 'your_custom_function', 10, 4); 

로 시험해 보다post_updated및 사용$post_after물건.https://codex.wordpress.org/Plugin_API/Action_Reference/post_updated

이것을 사용할 수 있다save_post훅을 사용할 수 있습니다.훅 우선순위를 100으로 변경하면 업데이트된 게시물이 제공됩니다.

add_action( 'save_post', 'send_mail_to_user', 100, 2 );

이것은 조금 오래된 것일 수 있지만 버전 5.6.0부터 새로운 후크를 사용할 수 있기 때문에 업데이트를 하고 싶습니다.갈고리는wp_after_insert_post그리고 당신은 여기에서 더 많은 정보를 찾을 수 있습니다.이 후크는 게시물이 작성 또는 업데이트되고 해당 조건과 메타가 모두 업데이트되면 트리거됩니다.다음은 예를 제시하겠습니다.

add_action( 'wp_after_insert_post', 'send_mail_to_user', 90, 4 );

/**
 * Callback to: 'wp_after_insert_post'
 * Fires once a post, its terms and meta data has been saved
 * @param int     $post_id Post ID.
 * @param WP_Post $post    Post object.
 * @param bool    $update  Whether this is an existing post being updated.
 * @param null|WP_Post $post_before Null for new posts, the WP_Post object prior to the update for updated posts.
 *
 */
public static function sync_product_registrations_on_update( $post_id, $post, $update, $post_before ) {

    if ( 'post' !== $post->post_type ) {
        //Only to process the below when post type is 'post' else return
        return;
    }

    if ( ! in_array( $post->post_status, [ 'private', 'publish' ] ) ) {
        //To only process when status is private or publish
        return;
    }

    //The rest of your code goes here


}

를 사용할 수 있습니다.rest_after_insert_{$this->post_type}(어디서) 후크$this->post_type포스트 타입(예: 'post' 또는 'myposttype')으로 대체됩니다.

링크에 대해 Florian Brinkmann에게 감사드립니다.

add_action('rest_after_insert_myposttype', 'myfunction', 10, 3);

function myfunction($post, $request, $creating) {
   // $creating is TRUE if the post is created for the first time,
   // false if it's an update

   //  ...
}

여기도 참조해 주세요.

일부 회피책은 $_POST['meta_field']를 위생과 함께 사용하는 것입니다.

$to_users = $_POST['vc_users'];
$to_program = $_POST['vc_program'];
$to_group = $_POST['vc_group'];
$to_excode = $_POST['vc_ex_code'];

$to_users = sanitize_text_field($to_users);
$to_program = sanitize_text_field($to_program);
$to_group = sanitize_text_field($to_group);
$to_excode = sanitize_text_field($to_excode);

필드명에 주의해 주세요.ACF 를 사용하면, 필드 키를 사용할 수 있습니다.

이 문제는 언뜻 보기보다 복잡합니다.

게시물이 업데이트되기 전에 'post_updated' 후크가 실행되므로 메타 데이터를 얻기 위한 모든 시도가 이전 데이터로 이루어집니다.또한 Wordpress(v5.7.2)는 투고가 저장된 후 훅이 없는 것 같습니다.

또한 'save_post' 후크는 리비전을 포함하여 저장 또는 작성된 모든 게시물에 대해 실행되며 $update boolean은 여전히 충분히 신뢰할 수 없기 때문에 매우 복잡합니다.

정확하고 간단한 답은wp_insert_post액션.

https://developer.wordpress.org/reference/hooks/wp_insert_post/

wp_insert_post 액션의 중요한 차이점은 update_post_meta가 호출된 후에 실행된다는 것입니다.

사용 가능한 파라미터는 3가지입니다.$update 플래그는 이것이 신규 또는 갱신된 투고인지 여부를 나타냅니다.

do_action( 'wp_insert_post', int $post_ID, WP_Post $post, bool $update )

따라서 - 모든 포스트 메타가 업데이트된 후 코드를 구현하려면 다음과 같이 사용하십시오.

add_action('wp_insert_post', 'run_after_post_updated', 10, 3);    
function run_after_post_updated($post_ID, $post, $update ) {
   //  ...
}

save_post 액션은 모든 메타데이터가 저장된 후에 함수를 호출할 수 있도록 높은 우선순위로 사용할 수 있습니다.

add_action( 'save_post',  'action_woocommerce_update_product', 20, 3 );
Here I have used higher priority 20

언급URL : https://stackoverflow.com/questions/44518752/which-wordpress-hook-fires-after-save-all-post-data-and-post-meta

반응형