programing

워드프레스 사용자 정의 게시글 유형에서 필드 유효성 검사 및 표시 오류

instargram 2023. 9. 24. 12:20
반응형

워드프레스 사용자 정의 게시글 유형에서 필드 유효성 검사 및 표시 오류

안녕하세요 여러분, 저는 몇 가지 작업 후 워드프레스에서 첫 번째 플러그인을 시작했습니다. 필드 검증에서 타격을 받았습니다.

문제는 제게라는 필드가 있다는 것입니다."preix_author_url"그리고 내 플러그인에서 나는 사용합니다.

add_action('save_post', 'my_function_name');

검증 클래스 예제를 만들었습니다.

<?php
class validator {
    public static function isUrl($str = '') {
        if(strlen($str) == 0)
            return FALSE;

        return preg_match('!^http(s)?://[\w-]+\.[\w-]+(\S+)?$!i',$str);
    }
}

인에"my_function_name()"

    function my_function_name(){
            global  $post;
            if(defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;
            if(isset($_POST['post_type']) && $_POST['post_type'] == 'wallpapers'){
                require_once( WALLP_FILE_PATH . '/wallp-core/wallp-validator.php' );                
                $validate = new validator();
                if(isset($_POST['preix_author_url'])){
                    if($validate->isUrl($_POST['preix_author_url']))
                        update_post_meta($post->ID, 'preix_author_url', $_POST['preix_author_url']);
                }
            }
        }

이제 validate return false를 확인하면 post page에 오류를 표시하고 싶습니다.하지만 저는 그 오류나 알림을 표시할 방법이 없었습니다.

그래서 시간이 좀 흐른 후에 저는 마침내 이것을 알아냈습니다.20분 안에 다시 찾아뵐 것을 약속드리지만 그렇게 쉬운 줄 알고 실패했습니다!!save_post hook에서 admin_notice가 작동하지 않는다는 것을 곳곳을 검색한 결과 알게 되었습니다!그래서 여기 당신의 문제에 대한 좋은 해결책이 있습니다.

    //for action hooks
add_action('save_post', 'my_function_name');
$validator = new Validator();
// called after the redirect
add_action('admin_head-post.php', array(&$validator, 'add_plugin_notice'));

//change your my_function_name with this
function my_function_name() {
    global $post;
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
        return;
    if (isset($_POST['post_type']) && $_POST['post_type'] == 'wallpapers') {
        require_once( WALLP_FILE_PATH . '/wallp-core/wallp-validator.php' );
        $validate = new validator();
        if (isset($_POST['preix_author_url'])) {
            //if($validate->isUrl($_POST['preix_author_url']))
            //update_post_meta(
            //$post->ID, 'preix_author_url', $_POST['preix_author_url']);
            $validator = new Validator();
            if (!$validator->isUrl($_POST['preix_author_url'])) {
                $validator->update_option(1);
                return;
            } else {
                update_post_meta(
                        $post->ID, 
                        'preix_author_url', $_POST['preix_author_url']);
            }
        }
    }
}

//ive also revised your class
class Validator {
    //new isUrl validation
    //better use filter_var than preg_match
    function isUrl($str = '') {
        if (filter_var($str, FILTER_VALIDATE_URL) === FALSE) {
            return FALSE;
        } else {
            return TRUE;
        }
    }

    //You can change the error message here. 
    //This for your your admin_notices hook
    function show_error() {
        echo '<div class="error">
       <p>Error Found!!</p>
       </div>';
    }

    //update option when admin_notices is needed or not
    function update_option($val) {
        update_option('display_my_admin_message', $val);
    }

    //function to use for your admin notice
    function add_plugin_notice() {
        if (get_option('display_my_admin_message') == 1) { 
            // check whether to display the message
            add_action('admin_notices', array(&$this, 'show_error'));
            // turn off the message
            update_option('display_my_admin_message', 0); 
        }
    }
}

개인 웹사이트에서 시도해봤는데 정말 잘 되더라구요!!저도 이것으로 많은 것을 배웠습니다!

언급URL : https://stackoverflow.com/questions/13216633/field-validation-and-displaying-error-in-wordpress-custom-post-type

반응형