it-source

WordPress 3.5 업로더에 새 이미지가 업로드되는 즉시 일부 코드를 실행하는 방법

criticalcode 2023. 3. 22. 21:39
반응형

WordPress 3.5 업로더에 새 이미지가 업로드되는 즉시 일부 코드를 실행하는 방법

WordPress 3.5 업로더에 새로운 이미지가 업로드되면 바로 코드를 실행해야 합니다.다음은 wp-includes/js/media-views.js 코드(529-540행)입니다.

    uploading: function( attachment ) {
        var content = this.frame.content;

        // If the uploader was selected, navigate to the browser.
        if ( 'upload' === content.mode() ) 
            this.frame.content.mode('browse');

        // If we're in a workflow that supports multiple attachments,
        // automatically select any uploading attachments.
        if ( this.get('multiple') )
            this.get('selection').add( attachment );
    },

이 업로드 기능 하단에 Alert('New image uploaded!')를 추가했고, 새로운 이미지가 업로드되면 브라우저에 'New image uploaded!'라고 알림이 표시되었습니다.하지만 WordPress의 핵심을 해킹하고 싶지 않기 때문에, 같은 일을 할 수 있는 코드를 테마에 쓸 수 있는 방법이 있을까요?제가 영어를 못해서 미안해요.경청해 주셔서 감사합니다.

wp-plupload.js 은 업로더 큐가 완료되었을 때 리셋됨을 나타냅니다.다음과 같이 할 수 있습니다.

wp.Uploader.queue.on('reset', function() { 
    alert('Upload Complete!');
});

테스트를 해봤는데 WP 3.5 사이트에서 작동합니다.

다음은 "새 미디어 업로드" 페이지의 일반 업로더와 "미디어 삽입" 대화상자의 새 업로더 모두에 대한 지원을 포함한 정식 버전입니다.

javascript 파일 이름:을 생성하여 아래 저장합니다./custom/js/폴더 또는 템플릿 디렉토리 내의 모든 폴더입니다.

// Hack for "Upload New Media" Page (old uploader)

// Overriding the uploadSuccess function:
if (typeof uploadSuccess !== 'undefined') {
    // First backup the function into a new variable.
    var uploadSuccess_original = uploadSuccess;
    // The original uploadSuccess function with has two arguments: fileObj, serverData
    // So we globally declare and override the function with two arguments (argument names shouldn't matter)
    uploadSuccess = function(fileObj, serverData) 
    {
        // Fire the original procedure with the same arguments
        uploadSuccess_original(fileObj, serverData);
        // Execute whatever you want here:
        alert('Upload Complete!');
    }
}

// Hack for "Insert Media" Dialog (new plupload uploader)

// Hooking on the uploader queue (on reset):
if (typeof wp.Uploader !== 'undefined' && typeof wp.Uploader.queue !== 'undefined') {
    wp.Uploader.queue.on('reset', function() { 
        alert('Upload Complete!');
    });
}

마지막으로 테마의 기능에 추가합니다.php 를 눌러 WP Admin에서 이 기능을 가져옵니다.

//You can also use other techniques to add/register the script for WP Admin.
function extend_admin_js() {
    wp_enqueue_script('wp-admin-extender.js', get_template_directory_uri().'/custom/js/wp-admin-extender.js', array('media-upload', 'swfupload', 'plupload'), false, true);
}
add_action('admin_enqueue_scripts', 'extend_admin_js');

이것은 정규 솔루션은 아닐 수 있지만 적어도 회피책입니다.

Onur Yldirlim의 답변은 모든 업로드 완료에 대한 후크를 제안하고 있습니다.하지만 당신의 질문에 따르면, 당신은 각각의 성공적인 업로드에 접속해야 합니다.WP를 확장하면 됩니다.Uploader.protype.jQuery에 대한 올바른 지침은 stackexchange 링크(https://wordpress.stackexchange.com/a/131295를 참조하십시오.

테스트한 결과, 실제로 "성공" 응답(및 init, error, added, progress, complete 등)에 접속할 수 있습니다.이 응답은 각 파일에 대해 개별적으로 "파일 업로드 완료"되어 비동기 업로드를 받습니다.php json 문자열.

Javascript에서는 다음과 같은 이점이 있습니다.

wp.media.view.Attachments.prototype.on('ready',function(){console.log('your code here');});

동작할 수 있는 액션이 php 코드에 있을 수도 있습니다.echo apply_filters("async_upload_{$type}", $id);비동기 접속 종료php.

add_attachment 액션에 접속할 수 있을까요?

function do_my_attachment_manipulation($attachment_ID)
{          
    $attachment = get_attached_file($attachment_ID); // Gets path to attachment
    // Javascript alert:
    ?>
         <script>
               alert('Media uploaded!');
         </script>
    <?php

}

add_action("add_attachment", 'do_my_attachment_manipulation');

https://wordpress.stackexchange.com/a/131295 링크 감사합니다.

이것은 정말 효과가 있는 훌륭한 솔루션입니다!

이 솔루션을 사용한 방법은 다음과 같습니다.

$.extend(wp.Uploader.prototype,{
    success: function(file_attachment){
        console.log(file_attachment);
        if(wp.media.frame.content.get() !== null){
            setTimeout(function(){
                wp.media.frame.content.get().collection.props.set({ignore: (+ new Date())});
            },100);
        }
    }
});

언급URL : https://stackoverflow.com/questions/14279786/how-to-run-some-code-as-soon-as-new-image-gets-uploaded-in-wordpress-3-5-uploade

반응형