워드프레스 플러그인: Keyword Link Plugin (V0.6) 수정

키워드에 따라 자동으로 하이퍼링크를 만들어 주는 플러그인을 찾다가 마침내, Keyword Link Plugin [1. Plugin Homepage: WordPress Keyword Link Plugin] [2. WordPress Plugin Page: BlogMechanics KeywordLink] 를 발견했습니다.

이것은 제가 그동안 찾고 싶었던 플러그인인데요, 제가 촛점으로 맞춘 기능은 다음과 같습니다.

  • 키워드를 넣고 거기에 따른 하이퍼링크를 자동으로 추가할 것
  • UTF-8을 지원할 것
  • 새창으로 열기 옵션이 있을 것

다 좋았는데, utf-8을 완벽하게 지원하지 안는 것 같았습니다. 그래서 몇가지 수정을 했구요, 또 “EDIT” 버튼을 눌렀을 때, 제대로 옵션을 표현하지 못하는 버그도 있고 해서 수정했습니다. 이 글은 제가 수정한 것을, 첫째는 저를 위한 노트가 될 듯 싶구요, 둘째는 이 수정을 다른 분들과 공유하고자 하여 글을 올립니다.

1. 버그: 옵션을 저장할때 제대로 기록하지 않는다.

Export/Import CSV를 이용하면, 이 문제가 사라지지만, 폼을 이용하여 수정하고 추가할때는 발생하는 문제입니다. 옵션을 선택하고 이것을 저장할때, 워드프레스의 option 테이블에 잘못된 정보를 기록하는 것이 문제였습니다. 문제를 보면, 예를 들어 플러그인 세팅 페이지에서 다음과 같이 입력하면,

Wordpress keyword link plugin option selection

정보가 사실은 “0|0|1|1|0” 와 같이 되어야 하지만, 실제 저장이 “||new window|ignore case|” 이와 같이 됩니다. 그래서 다시 EDIT 버튼을 누르면, 다음과 같이 나옵니다.

bug picture when edit button is clicked.

이 문제를 해결하기 위해 bm_getvalue() 함수를 추가했구요, bm_keywordlink_savenew() 함수를 다음과 같이 수정했습니다.

function bm_getvalue($var) {
     if ($var) {
	  return "1";
     } else {
	  return "0";
     }
}

function bm_keywordlink_savenew()
{
      $links = get_option(BM_KEYWORDLINK_OPTION);

		$keyword = $_POST['keyword'];
		$link = $_POST['link'];
		$nofollow = bm_getvalue($_POST['nofollow']);
 		$firstonly = bm_getvalue($_POST['firstonly']);
 		$newwindow = bm_getvalue($_POST['newwindow']);
 		$ignorecase = bm_getvalue($_POST['ignorecase']);
 		$isaffiliate = bm_getvalue($_POST['isaffiliate']); 

		if ($keyword == '' || $link == '')
		{
		  bm_keywordlink_topbarmessage(__('Please enter both a keyword and URL'));
		  return;
		}

		if (isset($links[$keyword]))
		{
		  bm_keywordlink_topbarmessage(__('Existing keyword has been updated'));
		}

 		/* Store the link */
	  $links[$keyword] = implode('|',array($link,$nofollow,$firstonly,$newwindow,$ignorecase,$isaffiliate));
	  update_option(BM_KEYWORDLINK_OPTION,$links);
}

이 이후에는 동작을 잘 했습니다.

2. UTF-8 지원문제

2-1. readme.txt에 있는 가이드라인을 따라하기

readme.txt에 보면, 아시아 언어를 쓰기 원한다면, bm_keywordlink.php에 있는 $regEx 변수값을 수정해야 한다고 되어 있습니다. 관련된 함수는 bm_keywordlink_replace() 인데요, 거의 마지막 부분에 다음을

$regEx = ''(?!((<.*?)|(<>]*?)>)|([^>]*?))'s' . $case;

다음으로 수정해 줍니다.

$regEx = ''(?!((<.*?)|(<>]*?)>)|([^>]*?))'s' . $case;

2-2. UTF-8을 지원하기 위한 decode64 추가

이미 javascript로 decode64() 함수가 이 플러그인에 있지만, 아시아 언어와는 동작을 제대로 하지 않는 것 같습니다. 그래서, 아시아언어를 같이 지원하기 위해 다른 javascript code를 WebToolKit site에서 가져왔습니다. 다음은 그 부분입니다.

/**
*
*  Base64 encode / decode
*  http://www.webtoolkit.info/
*
**/

var Base64 = {

    // private property
    _keyStr : "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",

    // public method for encoding
    encode : function (input) {
        var output = "";
        var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
        var i = 0;

        input = Base64._utf8_encode(input);

        while (i < input.length) {

            chr1 = input.charCodeAt(i++);
            chr2 = input.charCodeAt(i++);
            chr3 = input.charCodeAt(i++);

            enc1 = chr1 >> 2;
            enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
            enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
            enc4 = chr3 & 63;

            if (isNaN(chr2)) {
                enc3 = enc4 = 64;
            } else if (isNaN(chr3)) {
                enc4 = 64;
            }

            output = output +
            this._keyStr.charAt(enc1) + this._keyStr.charAt(enc2) +
            this._keyStr.charAt(enc3) + this._keyStr.charAt(enc4);

        }

        return output;
    },

    // public method for decoding
    decode : function (input) {
        var output = "";
        var chr1, chr2, chr3;
        var enc1, enc2, enc3, enc4;
        var i = 0;

        input = input.replace(/[^A-Za-z0-9+/=]/g, "");

        while (i < input.length) {

            enc1 = this._keyStr.indexOf(input.charAt(i++));
            enc2 = this._keyStr.indexOf(input.charAt(i++));
            enc3 = this._keyStr.indexOf(input.charAt(i++));
            enc4 = this._keyStr.indexOf(input.charAt(i++));

            chr1 = (enc1 << 2) | (enc2 >> 4);
            chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
            chr3 = ((enc3 & 3) << 6) | enc4;

            output = output + String.fromCharCode(chr1);

            if (enc3 != 64) {
                output = output + String.fromCharCode(chr2);
            }
            if (enc4 != 64) {
                output = output + String.fromCharCode(chr3);
            }

        }

        output = Base64._utf8_decode(output);

        return output;

    },

    // private method for UTF-8 encoding
    _utf8_encode : function (string) {
        string = string.replace(/rn/g,"n");
        var utftext = "";

        for (var n = 0; n < string.length; n++) {

            var c = string.charCodeAt(n);

            if (c < 128) {
                utftext += String.fromCharCode(c);
            }
            else if((c > 127) && (c < 2048)) {
                utftext += String.fromCharCode((c >> 6) | 192);
                utftext += String.fromCharCode((c & 63) | 128);
            }
            else {
                utftext += String.fromCharCode((c >> 12) | 224);
                utftext += String.fromCharCode(((c >> 6) & 63) | 128);
                utftext += String.fromCharCode((c & 63) | 128);
            }

        }

        return utftext;
    },

    // private method for UTF-8 decoding
    _utf8_decode : function (utftext) {
        var string = "";
        var i = 0;
        var c = c1 = c2 = 0;

        while ( i < utftext.length ) {

            c = utftext.charCodeAt(i);

            if (c < 128) {
                string += String.fromCharCode(c);
                i++;
            }
            else if((c > 191) && (c < 224)) {
                c2 = utftext.charCodeAt(i+1);
                string += String.fromCharCode(((c & 31) << 6) | (c2 & 63));
                i += 2;
            }
            else {
                c2 = utftext.charCodeAt(i+1);
                c3 = utftext.charCodeAt(i+2);
                string += String.fromCharCode(((c & 15) << 12) | ((c2 & 63) << 6) | (c3 & 63));
                i += 3;
            }

        }

        return string;
    }

}
&#91;/sourcecode&#93;</pre>
또한, BMEditKeyword() 함수를 다음과 같이 수정합니다.
<pre>[sourcecode language='php']
function BMEditKeyword(keyword,url,nofollow,firstonly,newwindow,ignorecase,isaffiliate)
		{
 			 document.bm_keywordadd.keyword.value      = Base64.decode(keyword);
			 document.bm_keywordadd.link.value         = Base64.decode(url);
			 document.bm_keywordadd.nofollow.checked   = (nofollow==1);
			 document.bm_keywordadd.firstonly.checked  = (firstonly==1);
			 document.bm_keywordadd.newwindow.checked  = (newwindow==1);
			 document.bm_keywordadd.ignorecase.checked = (ignorecase==1);
			 document.bm_keywordadd.isaffiliate.checked= (isaffiliate==1);
			 window.location.hash = "keywordeditor";
		}

2.1 와 2.2 는 utf-8을 지원하기 위해 반드시 필요한 작업이었습니다. 이 이후에 “EDIT” 버튼을 누르면, 기존에는 아시아문자 (예:한국어)를 가져오지 못했지만, 이제는 폼으로 잘 가져오게 되네요.

이제 키워드를 등록하고 자동으로 하이퍼링크를 만들어주는 플러그인을 즐기시면 됩니다. 🙂

You May Also Like

9 Comments

    1. 아, 좋은 정보 감사합니다. 테스트 해보고 저도 적용을 해봐야 겠네요. 🙂

      감사합니다.

    1. 네, 아마도 제가 나중에 시간이 될때 수정된 파일을 올려서 링크하는게 도움이 될 수도 있겠네요. 원저자와 한번 얘기해 봐야겠습니다.

브레드에 답글 남기기 응답 취소

이메일 주소는 공개되지 않습니다. 필수 필드는 *로 표시됩니다