← Back
Editing: functions.php.save.1
<?php /** * GeneratePress child theme functions and definitions. * * Add your custom PHP in this file. * Only edit this file if you have direct access to it on your server (to fix errors if they happen). */ // 새로운 코드 시작 add_action('rest_api_init', function () { // 기존 /price 엔드포인트 register_rest_route('stock/v1', '/price', array( 'methods' => 'GET', 'callback' => 'get_stock_price', 'permission_callback' => '__return_true', // 필요 시 보안 강화 가능 )); // 새로운 /historical 엔드포인트 추가 register_rest_route('stock/v1', '/historical', array( 'methods' => 'GET', 'callback' => 'get_historical_stock_data', 'permission_callback' => '__return_true', // 필요 시 보안 강화 가능 )); }); function get_stock_price(WP_REST_Request $request) { $symbol = sanitize_text_field($request->get_param('symbol')); $itmsNm = sanitize_text_field($request->get_param('itmsNm')); // 주식 심볼과 ISIN 코드 매핑 $mapping = array( '005930' => 'KR7005930003', // 삼성전자 '삼성전자' => 'KR7005930003', '000660' => 'KR7005930004', // SK하이닉스 'SK하이닉스' => 'KR7005930004', // 필요한 주식 심볼과 ISIN 코드 추가 // 예: // '035420' => 'KR0000000354', // NAVER (실제 ISIN 코드로 변경 필요) // 'NAVER' => 'KR0000000354', ); // API 키 설정 $api_key = 'fJAqcEIgPekLuQbKV1SVf6hTwI8fq48Hsh9DLQACUzPRdLcY%2BbEj8JoN%2F3Mc6JUOddNK8fYX%2BWtAjCkxnS62kg%3D%3D'; $api_endpoint = 'https://apis.data.go.kr/1160100/service/GetStockSecuritiesInfoService/getStockPriceInfo'; // 요청 파라미터 구성 $params = array( 'serviceKey' => $api_key, 'numOfRows' => 1, 'pageNo' => 1, 'resultType' => 'json', // JSON 형식으로 요청 ); if (array_key_exists($symbol, $mapping)) { $params['isinCd'] = $mapping[$symbol]; } elseif (!empty($itmsNm)) { $params['itmsNm'] = $itmsNm; } else { return new WP_Error('invalid_request', 'symbol 또는 itmsNm 파라미터가 필요합니다.', array('status' => 400)); } // API URL 구성 $url = add_query_arg($params, $api_endpoint); // API 호출 $response = wp_remote_get($url); if (is_wp_error($response)) { return new WP_Error('api_error', 'API 호출에 실패했습니다.', array('status' => 500)); } $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); // 응답 데이터 검증 if (isset($data['response']['header']['resultCode']) && $data['response']['header']['resultCode'] === '00') { if (isset($data['response']['body']['items']['item'][0]['clpr'])) { $currentPrice = floatval($data['response']['body']['items']['item'][0]['clpr']); return rest_ensure_response(array('currentPrice' => $currentPrice)); } else { return new WP_Error('no_data', '시세 데이터를 찾을 수 없습니다.', array('status' => 404)); } } else { $resultMsg = isset($data['response']['header']['resultMsg']) ? $data['response']['header']['resultMsg'] : '알 수 없는 오류가 발생했습니다.'; return new WP_Error('api_error', $resultMsg, array('status' => 500)); } } function get_historical_stock_data(WP_REST_Request $request) { $symbol = sanitize_text_field($request->get_param('symbol')); $itmsNm = sanitize_text_field($request->get_param('itmsNm')); $beginBasDt = sanitize_text_field($request->get_param('beginBasDt')); $endBasDt = sanitize_text_field($request->get_param('endBasDt')); // 주식 심볼과 ISIN 코드 매핑 $mapping = array( '005930' => 'KR7005930003', // 삼성전자 '삼성전자' => 'KR7005930003', '000660' => 'KR7005930004', // SK하이닉스 'SK하이닉스' => 'KR7005930004', // 필요한 주식 심볼과 ISIN 코드 추가 // 예: // '035420' => 'KR0000000354', // NAVER (실제 ISIN 코드로 변경 필요) // 'NAVER' => 'KR0000000354', ); // API 키 설정 $api_key = 'fJAqcEIgPekLuQbKV1SVf6hTwI8fq48Hsh9DLQACUzPRdLcY%2BbEj8JoN%2F3Mc6JUOddNK8fYX%2BWtAjCkxnS62kg%3D%3D'; $api_endpoint = 'https://apis.data.go.kr/1160100/service/GetStockSecuritiesInfoService/getStockPriceInfo'; // 요청 파라미터 구성 $params = array( 'serviceKey' => $api_key, 'numOfRows' => 100, // 한 페이지당 최대 결과 수 'pageNo' => 1, 'resultType' => 'json', // JSON 형식으로 요청 'beginBasDt' => $beginBasDt, 'endBasDt' => $endBasDt, ); if (array_key_exists($symbol, $mapping)) { $params['isinCd'] = $mapping[$symbol]; } elseif (!empty($itmsNm)) { $params['itmsNm'] = $itmsNm; } else { return new WP_Error('invalid_request', 'symbol 또는 itmsNm 파라미터가 필요합니다.', array('status' => 400)); } // API URL 구성 $url = add_query_arg($params, $api_endpoint); // API 호출 $response = wp_remote_get($url); if (is_wp_error($response)) { return new WP_Error('api_error', 'API 호출에 실패했습니다.', array('status' => 500)); } $body = wp_remote_retrieve_body($response); $data = json_decode($body, true); // 응답 데이터 검증 if (isset($data['response']['header']['resultCode']) && $data['response']['header']['resultCode'] === '00') { if (isset($data['response']['body']['items']['item'])) { $items = $data['response']['body']['items']['item']; // 다중 페이지 처리 (필요 시) $totalCount = intval($data['response']['body']['totalCount']); $pages = ceil($totalCount / 100); for ($i = 2; $i <= $pages; $i++) { $params['pageNo'] = $i; $url = add_query_arg($params, $api_endpoint); $response = wp_remote_get($url); if (!is_wp_error($response)) { $body = wp_remote_retrieve_body($response); $data_page = json_decode($body, true); if (isset($data_page['response']['body']['items']['item'])) { $items = array_merge($items, $data_page['response']['body']['items']['item']); } } } // 필요한 데이터만 필터링 $historicalPrices = array_map(function($item) { return array( 'basDt' => $item['basDt'], 'mkp' => $item['mkp'], // 시가 'hipr' => $item['hipr'], // 고가 'lopr' => $item['lopr'], // 저가 'clpr' => $item['clpr'], // 종가 'itmsNm' => $item['itmsNm'], // 종목명 ); }, $items); return rest_ensure_response(array( 'historicalPrices' => $historicalPrices )); } else { return new WP_Error('no_data', '시세 데이터를 찾을 수 없습니다.', array('status' => 404)); } } else { $resultMsg = isset($data['response']['header']['resultMsg']) ? $data['response']['header']['resultMsg'] : '알 수 없는 오류가 발생했습니다.'; return new WP_Error('api_error', $resultMsg, array('status' => 500)); } } // 새로운 코드 끝 // 나이 계산기 // API 인증키 (Decoding 된 값 사용) define('KASI_API_KEY', 'fJAqcEIgPekLuQbKV1SVf6hTwI8fq48Hsh9DLQACUzPRdLcY+bEj8JoN/3Mc6JUOddNK8fYX+WtAjCkxnS62kg=='); // AJAX 액션 등록 (비로그인/로그인 모두 허용) add_action('wp_ajax_nopriv_my_age_calculator', 'my_age_calculator'); add_action('wp_ajax_my_age_calculator', 'my_age_calculator'); function my_age_calculator() { // 입력값 받기 $birth_type = isset($_POST['birth_type']) ? sanitize_text_field($_POST['birth_type']) : ''; $year = isset($_POST['year']) ? intval($_POST['year']) : 0; $month = isset($_POST['month']) ? intval($_POST['month']) : 0; $day = isset($_POST['day']) ? intval($_POST['day']) : 0; if (!$birth_type || !$year || !$month || !$day) { wp_send_json_error('입력값이 올바르지 않습니다.'); wp_die(); } // 양력 입력 시 : 음력 정보 조회 (양력 → 음력 변환 API 호출) if ($birth_type === 'solar') { $formattedMonth = sprintf("%02d", $month); $formattedDay = sprintf("%02d", $day); $url = "http://apis.data.go.kr/B090041/openapi/service/LrsrCldInfoService/getLunCalInfo?solYear={$year}&solMonth={$formattedMonth}&solDay={$formattedDay}&ServiceKey=" . urlencode(KASI_API_KEY); $response = file_get_contents($url); if (!$response) { wp_send_json_error('API 호출 실패 (양력→음력).'); wp_die(); } $xml = simplexml_load_string($response); if (!$xml || !isset($xml->body->items->item)) { wp_send_json_error('API 응답 오류 (양력→음력).'); wp_die(); } $item = $xml->body->items->item; $lunar_year = (int)$item->lunYear; $lunar_month = (int)$item->lunMonth; $lunar_day = (int)$item->lunDay; $result['음력생일'] = sprintf("%04d-%02d-%02d", $lunar_year, $lunar_month, $lunar_day); // 나이 및 별자리 계산은 입력한 양력 생일 사용 $solar_date = sprintf("%04d-%02d-%02d", $year, $month, $day); $birth_date = new DateTime($solar_date); } // 음력 입력 시 : 양력 정보 조회 (음력 → 양력 변환 API 호출) else { $formattedMonth = sprintf("%02d", $month); $formattedDay = sprintf("%02d", $day); $url = "http://apis.data.go.kr/B090041/openapi/service/LrsrCldInfoService/getSolCalInfo?lunYear={$year}&lunMonth={$formattedMonth}&lunDay={$formattedDay}&ServiceKey=" . urlencode(KASI_API_KEY); $response = file_get_contents($url); if (!$response) { wp_send_json_error('API 호출 실패 (음력→양력).'); wp_die(); } $xml = simplexml_load_string($response); if (!$xml || !isset($xml->body->items->item)) { wp_send_json_error('API 응답 오류 (음력→양력).'); wp_die(); } $item = $xml->body->items->item; $solar_year = (int)$item->solYear; $solar_month = (int)$item->solMonth; $solar_day = (int)$item->solDay; $result['양력생일'] = sprintf("%04d-%02d-%02d", $solar_year, $solar_month, $solar_day); $solar_date = sprintf("%04d-%02d-%02d", $solar_year, $solar_month, $solar_day); $birth_date = new DateTime($solar_date); $lunar_year = $year; // 띠 계산용 } // 만나이 (국제나이): 오늘과 생일 차이 연도 $today = new DateTime(); $diff = $today->diff($birth_date); $result['만나이'] = $diff->y; // 연나이 (한국식 나이): 현재년도 - 생년 + 1 (양력 기준) $result['연나이'] = date('Y') - (int)$birth_date->format('Y') + 1; // 띠 계산 (음력 연도 기준; (연도-4)%12) if (!isset($lunar_year)) { // 양력 입력의 경우 API 응답에서 가져옴 $lunar_year = (int)$item->lunYear; } $zodiacs = array("쥐", "소", "호랑이", "토끼", "용", "뱀", "말", "양", "원숭이", "닭", "개", "돼지"); $result['띠'] = $zodiacs[ ($lunar_year - 4) % 12 ]; // 별자리 (양력 생일 기준) $m = (int)$birth_date->format('m'); $d = (int)$birth_date->format('d'); if (($m == 1 && $d >= 20) || ($m == 2 && $d <= 18)) { $star = "물병자리"; } elseif (($m == 2 && $d >= 19) || ($m == 3 && $d <= 20)) { $star = "물고기자리"; } elseif (($m == 3 && $d >= 21) || ($m == 4 && $d <= 19)) { $star = "양자리"; } elseif (($m == 4 && $d >= 20) || ($m == 5 && $d <= 20)) { $star = "황소자리"; } elseif (($m == 5 && $d >= 21) || ($m == 6 && $d <= 21)) { $star = "쌍둥이자리"; } elseif (($m == 6 && $d >= 22) || ($m == 7 && $d <= 22)) { $star = "게자리"; } elseif (($m == 7 && $d >= 23) || ($m == 8 && $d <= 22)) { $star = "사자자리"; } elseif (($m == 8 && $d >= 23) || ($m == 9 && $d <= 22)) { $star = "처녀자리"; } elseif (($m == 9 && $d >= 23) || ($m == 10 && $d <= 22)) { $star = "천칭자리"; } elseif (($m == 10 && $d >= 23) || ($m == 11 && $d <= 22)) { $star = "전갈자리"; } elseif (($m == 11 && $d >= 23) || ($m == 12 && $d <= 21)) { $star = "사수자리"; } else { $star = "염소자리"; } $result['별자리'] = $star; wp_send_json_success($result); wp_die(); } // 나이 계산기 끝 // 네이버 지도 api 시작 function enqueue_naver_map_script() { // 네이버 지도 API 스크립트를 wp_enqueue_script()를 사용하여 등록합니다. wp_enqueue_script( 'naver-map', 'https://openapi.map.naver.com/openapi/v3/maps.js?ncpClientId=xuyqpl9e6q', array(), null, true ); } add_action( 'wp_enqueue_scripts', 'enqueue_naver_map_script' ); // 네이버 지도 api 끝 add_filter('widget_text', 'do_shortcode'); // 영문 주소 API 시작 // 승인키 상수 정의 define('JUSO_ENG_API_KEY', 'U01TX0FVVEgyMDI1MDMxODIyMDAzMzExNTU1ODk='); define('JUSO_KOR_API_KEY', 'U01TX0FVVEgyMDI1MDMxOTEzNTUwMjExNTU2MTc='); // 로그인 여부와 상관없이 AJAX 액션 등록 add_action('wp_ajax_convert_address', 'convert_address_ajax'); add_action('wp_ajax_nopriv_convert_address', 'convert_address_ajax'); function convert_address_ajax() { // 입력받은 주소(keyword) sanitizing $keyword = isset($_POST['keyword']) ? sanitize_text_field($_POST['keyword']) : ''; if (empty($keyword)) { wp_send_json_error('주소를 입력해 주세요.'); } // 기본 요청 파라미터 설정 $currentPage = 1; $countPerPage = 10; $resultType = 'json'; // 1) 영문주소 검색 API 호출 URL 구성 $eng_api_url = 'https://business.juso.go.kr/addrlink/addrEngApi.do?currentPage=' . $currentPage . '&countPerPage=' . $countPerPage . '&keyword=' . urlencode($keyword) . '&confmKey=' . JUSO_ENG_API_KEY . '&resultType=' . $resultType; // 2) 한글 도로명주소 검색 API 호출 URL 구성 $kor_api_url = 'https://business.juso.go.kr/addrlink/addrLinkApi.do?currentPage=' . $currentPage . '&countPerPage=' . $countPerPage . '&keyword=' . urlencode($keyword) . '&confmKey=' . JUSO_KOR_API_KEY . '&resultType=' . $resultType; // 영문주소 API 호출 (wp_remote_get 이용) $eng_response = wp_remote_get($eng_api_url); if (is_wp_error($eng_response)) { wp_send_json_error('영문주소 API 호출에 실패했습니다.'); } $eng_body = wp_remote_retrieve_body($eng_response); $eng_data = json_decode($eng_body, true); // 한글 도로명주소 API 호출 $kor_response = wp_remote_get($kor_api_url); if (is_wp_error($kor_response)) { wp_send_json_error('한글주소 API 호출에 실패했습니다.'); } $kor_body = wp_remote_retrieve_body($kor_response); $kor_data = json_decode($kor_body, true); // 검색 결과 유효성 검사 (각 API에서 첫번째 결과 사용) if (!isset($eng_data['results']) || !isset($eng_data['results']['juso'][0])) { wp_send_json_error('영문 주소 검색 결과가 없습니다.'); } if (!isset($kor_data['results']) || !isset($kor_data['results']['juso'][0])) { wp_send_json_error('한글 주소 검색 결과가 없습니다.'); } $eng_result = $eng_data['results']['juso'][0]; $kor_result = $kor_data['results']['juso'][0]; // 두 API 결과를 합쳐서 배열 생성 $merged_result = array( 'engRoadAddr' => isset($eng_result['roadAddr']) ? $eng_result['roadAddr'] : '', 'engJibunAddr' => isset($eng_result['jibunAddr']) ? $eng_result['jibunAddr'] : '', 'zipNo' => isset($eng_result['zipNo']) ? $eng_result['zipNo'] : '', 'korRoadAddr' => isset($kor_result['roadAddr']) ? $kor_result['roadAddr'] : '', // 기존의 '한글 기준 영문주소(옵션)' 대신 한글 도로명주소 API의 jibunAddr 필드 사용 (한글 지번주소) 'korJibunAddr' => isset($kor_result['jibunAddr']) ? $kor_result['jibunAddr'] : '' ); // 필요시 필터로 결과를 수정할 수 있음 $merged_result = apply_filters('custom_convert_address_result', $merged_result, $keyword); wp_send_json_success($merged_result); } // 영문 주소 API 끝 // 한글 영문 변환기 시작 // 국립국어원 한글-로마자 변환 API 연동 함수 function korean_to_roman_api_init() { // API 호출 함수 등록 add_action('wp_ajax_translate_korean', 'translate_korean_ajax'); add_action('wp_ajax_nopriv_translate_korean', 'translate_korean_ajax'); // 필요한 스크립트 등록 add_action('wp_enqueue_scripts', 'enqueue_converter_scripts'); } add_action('init', 'korean_to_roman_api_init'); // 필요한 스크립트 등록 함수 function enqueue_converter_scripts() { wp_enqueue_script('jquery'); // AJAX URL을 전역 변수로 등록 wp_localize_script('jquery', 'korean_converter', array( 'ajax_url' => admin_url('admin-ajax.php'), 'service_key' => '0547125c-0e49-4d47-a63a-ef9c213dda5a', 'nonce' => wp_create_nonce('translate_korean_nonce') )); } // AJAX 처리 함수 function translate_korean_ajax() { // 보안 검사 check_ajax_referer('translate_korean_nonce', 'nonce'); $text = isset($_POST['text']) ? sanitize_text_field($_POST['text']) : ''; if (empty($text)) { wp_send_json_error('텍스트를 입력해주세요.'); wp_die(); } // 두 가지 방식으로 변환 $current_result = current_romanization($text); $traditional_result = traditional_romanization($text); // 결과 조합 $combined_result = format_combined_result($text, $current_result, $traditional_result); if (!empty($combined_result)) { wp_send_json_success($combined_result); } else { wp_send_json_error('변환 중 오류가 발생했습니다.'); } wp_die(); } // 현행 로마자 표기법(2000년 개정)에 따른 변환 function current_romanization($text) { // 초성 매핑 $cho = array( 'ㄱ' => 'g', 'ㄲ' => 'kk', 'ㄴ' => 'n', 'ㄷ' => 'd', 'ㄸ' => 'tt', 'ㄹ' => 'r', 'ㅁ' => 'm', 'ㅂ' => 'b', 'ㅃ' => 'pp', 'ㅅ' => 's', 'ㅆ' => 'ss', 'ㅇ' => '', 'ㅈ' => 'j', 'ㅉ' => 'jj', 'ㅊ' => 'ch', 'ㅋ' => 'k', 'ㅌ' => 't', 'ㅍ' => 'p', 'ㅎ' => 'h' ); $jung = array( 'ㅏ' => 'a', 'ㅐ' => 'ae', 'ㅑ' => 'ya', 'ㅒ' => 'yae', 'ㅓ' => 'eo', 'ㅔ' => 'e', 'ㅕ' => 'yeo', 'ㅖ' => 'ye', 'ㅗ' => 'o', 'ㅘ' => 'wa', 'ㅙ' => 'wae', 'ㅚ' => 'oe', 'ㅛ' => 'yo', 'ㅜ' => 'u', 'ㅝ' => 'wo', 'ㅞ' => 'we', 'ㅟ' => 'wi', 'ㅠ' => 'yu', 'ㅡ' => 'eu', 'ㅢ' => 'ui', 'ㅣ' => 'i' ); $jong = array( '' => '', 'ㄱ' => 'k', 'ㄲ' => 'k', 'ㄳ' => 'k', 'ㄴ' => 'n', 'ㄵ' => 'n', 'ㄶ' => 'n', 'ㄷ' => 't', 'ㄹ' => 'l', 'ㄺ' => 'k', 'ㄻ' => 'm', 'ㄼ' => 'l', 'ㄽ' => 'l', 'ㄾ' => 'l', 'ㄿ' => 'p', 'ㅀ' => 'l', 'ㅁ' => 'm', 'ㅂ' => 'p', 'ㅄ' => 'p', 'ㅅ' => 't', 'ㅆ' => 't', 'ㅇ' => 'ng', 'ㅈ' => 't', 'ㅊ' => 't', 'ㅋ' => 'k', 'ㅌ' => 't', 'ㅍ' => 'p', 'ㅎ' => 't' ); // 현행 로마자 표기법에 따른 성씨 특별 처리 (모두 대문자) $surnames_current = array( '김' => 'GIM', '이' => 'I', '박' => 'BAK', '최' => 'CHOE', '정' => 'JEONG', '강' => 'GANG', '조' => 'JO', '윤' => 'YUN', '장' => 'JANG', '임' => 'IM', '한' => 'HAN', '오' => 'O', '서' => 'SEO', '신' => 'SIN', '권' => 'GWON', '황' => 'HWANG', '안' => 'AN', '송' => 'SONG', '전' => 'JEON', '홍' => 'HONG' ); return romanize_text($text, $cho, $jung, $jong, $surnames_current); } // 매큔-라이샤워 방식에 따른 변환 function traditional_romanization($text) { // 초성 매핑 (매큔-라이샤워 방식) $cho = array( 'ㄱ' => 'k', 'ㄲ' => 'kk', 'ㄴ' => 'n', 'ㄷ' => 't', 'ㄸ' => 'tt', 'ㄹ' => 'r', 'ㅁ' => 'm', 'ㅂ' => 'p', 'ㅃ' => 'pp', 'ㅅ' => 's', 'ㅆ' => 'ss', 'ㅇ' => '', 'ㅈ' => 'ch', 'ㅉ' => 'tch', 'ㅊ' => 'ch\'', 'ㅋ' => 'k\'', 'ㅌ' => 't\'', 'ㅍ' => 'p\'', 'ㅎ' => 'h' ); $jung = array( 'ㅏ' => 'a', 'ㅐ' => 'ae', 'ㅑ' => 'ya', 'ㅒ' => 'yae', 'ㅓ' => 'ŏ', 'ㅔ' => 'e', 'ㅕ' => 'yŏ', 'ㅖ' => 'ye', 'ㅗ' => 'o', 'ㅘ' => 'wa', 'ㅙ' => 'wae', 'ㅚ' => 'oe', 'ㅛ' => 'yo', 'ㅜ' => 'u', 'ㅝ' => 'wŏ', 'ㅞ' => 'we', 'ㅟ' => 'wi', 'ㅠ' => 'yu', 'ㅡ' => 'ŭ', 'ㅢ' => 'ŭi', 'ㅣ' => 'i' ); $jong = array( '' => '', 'ㄱ' => 'k', 'ㄲ' => 'k', 'ㄳ' => 'k', 'ㄴ' => 'n', 'ㄵ' => 'n', 'ㄶ' => 'n', 'ㄷ' => 't', 'ㄹ' => 'l', 'ㄺ' => 'k', 'ㄻ' => 'm', 'ㄼ' => 'l', 'ㄽ' => 'l', 'ㄾ' => 'l', 'ㄿ' => 'p', 'ㅀ' => 'l', 'ㅁ' => 'm', 'ㅂ' => 'p', 'ㅄ' => 'p', 'ㅅ' => 't', 'ㅆ' => 't', 'ㅇ' => 'ng', 'ㅈ' => 't', 'ㅊ' => 't', 'ㅋ' => 'k', 'ㅌ' => 't', 'ㅍ' => 'p', 'ㅎ' => 't' ); // 매큔-라이샤워 방식에 따른 성씨 특별 처리 (모두 대문자) $surnames_traditional = array( '김' => 'KIM', '이' => 'LEE', '박' => 'PARK', '최' => 'CHOI', '정' => 'JUNG', '강' => 'KANG', '조' => 'CHO', '윤' => 'YOON', '장' => 'CHANG', '임' => 'LIM', '한' => 'HAN', '오' => 'O', '서' => 'SUH', '신' => 'SHIN', '권' => 'KWON', '황' => 'HWANG', '안' => 'AHN', '송' => 'SONG', '전' => 'CHUN', '홍' => 'HONG' ); return romanize_text($text, $cho, $jung, $jong, $surnames_traditional); } // 공통 로마자 변환 함수 function romanize_text($text, $cho, $jung, $jong, $surnames) { $result = ''; $len = mb_strlen($text, 'UTF-8'); // 첫 글자가 성씨인지 확인 $first_char = mb_substr($text, 0, 1, 'UTF-8'); if (isset($surnames[$first_char])) { $result .= $surnames[$first_char]; $start_idx = 1; } else { $start_idx = 0; } // 나머지 글자 처리 for ($i = $start_idx; $i < $len; $i++) { $char = mb_substr($text, $i, 1, 'UTF-8'); $code = mb_ord($char, 'UTF-8'); // 한글 유니코드 범위 (0xAC00 ~ 0xD7A3) if ($code >= 0xAC00 && $code <= 0xD7A3) { $code -= 0xAC00; $cho_idx = (int)($code / (21 * 28)); $jung_idx = (int)(($code % (21 * 28)) / 28); $jong_idx = $code % 28; $cho_keys = array_keys($cho); $jung_keys = array_keys($jung); $jong_keys = array_keys($jong); $cho_char = isset($cho_keys[$cho_idx]) ? $cho[$cho_keys[$cho_idx]] : ''; $jung_char = isset($jung_keys[$jung_idx]) ? $jung[$jung_keys[$jung_idx]] : ''; $jong_char = isset($jong_keys[$jong_idx]) ? $jong[$jong_keys[$jong_idx]] : ''; $result .= $cho_char . $jung_char . $jong_char; } else { // 한글이 아닌 경우 그대로 추가 $result .= $char; } } // 전체 대문자로 변경 return strtoupper($result); } // 두 결과를 조합하여 포맷팅 function format_combined_result($text, $current, $traditional) { $result = '<div class="romanization-results">'; // 입력 텍스트 $result .= '<div class="input-text"><strong>입력:</strong> ' . esc_html($text) . '</div>'; // 현행 로마자 표기법 결과 $result .= '<div class="result-item">'; $result .= '<div class="result-type">현행 로마자 표기법 (2000년 개정):</div>'; $result .= '<div class="result-value">' . esc_html($current) . ' <button class="copy-btn" data-copy="' . esc_attr($current) . '">복사하기</button></div>'; $result .= '</div>'; // 두 결과가 다를 경우에만 전통적 표기법 결과 표시 if ($current !== $traditional) { $result .= '<div class="result-item">'; $result .= '<div class="result-type">매큔-라이샤워 표기법 (전통적 표기):</div>'; $result .= '<div class="result-value">' . esc_html($traditional) . ' <button class="copy-btn" data-copy="' . esc_attr($traditional) . '">복사하기</button></div>'; $result .= '</div>'; } $result .= '</div>'; return $result; } // 한글 영문 변환기 끝 // JSON 타입 허용 끝 function custom_upload_mimes( $mimes ) { // .json 파일 허용 $mimes['json'] = 'application/json'; // .bin 파일 허용 $mimes['bin'] = 'application/octet-stream'; return $mimes; } add_filter( 'upload_mimes', 'custom_upload_mimes' ); function allow_json_filetype( $data, $file, $filename, $mimes ) { if ( empty( $data['ext'] ) || empty( $data['type'] ) ) { $exploded = explode( '.', $filename ); $ext = strtolower( end( $exploded ) ); if ( 'json' === $ext ) { $data['ext'] = 'json'; $data['type'] = 'application/json'; } } return $data; } add_filter( 'wp_check_filetype_and_ext', 'allow_json_filetype', 10, 4 ); // JSON 타입 허용 끝 // 건물번호검색 api 시작 // get_building_data.php header('Content-Type: application/json; charset=utf-8'); // 검색어가 전달되지 않은 경우 에러 메시지 출력 if (!isset($_GET['juso_keyword']) || empty($_GET['juso_keyword'])) { echo json_encode(['error' => '검색어가 누락되었습니다.']); exit; } // 입력된 검색어를 안전하게 처리하고 URL 인코딩 $keyword = urlencode(strip_tags($_GET['juso_keyword'])); // API 키 (제공받은 키 사용) $api_key = 'U01TX0FVVEgyMDI1MDMxOTEzNTUwMjExNTU2MTY='; // JSON 결과를 요청하는 API 호출 URL 설정 $api_url = 'https://business.juso.go.kr/addrlink/addrLinkApi.do?currentPage=1&countPerPage=10' . '&keyword=' . $keyword . '&confmKey=' . $api_key . '&resultType=json'; // API 호출 $response = file_get_contents($api_url); if ($response === false) { echo json_encode(['error' => 'API 호출에 실패했습니다.']); exit; } // API에서 받은 JSON 결과를 그대로 출력 echo $response; // 건물번호검색 api 끝
Save File
Cancel