WordPress 플러그인 – 노트의 내용을 워드프레스 블록 형식으로 변경 후 포스팅

옵시디언

WordPress 플러그인 – 이미지 업로드 이슈 수정을 통해서 이미지 업로드 문제는 해결했다.

다음은 포스팅 글의 레이아웃 후속 수정을 최소화하기 위한 수정들을 하려고 한다. 수정 전 플러그인은 옵시디언 노트 본문이 모두 html태그로 변환되서 포스팅된다. 그래서 포스팅 이후 편집에 들어가면 블록 편집이 아닌 클래식 편집기로 편집이 된다.

여기에서 블록 변환을 하게 되면 워드프레스에서 다시 내용 변환이 되면서 html태그 변경 단계에서 적용된 커스텀 사항들이 초기화될 확률이 높다. 이걸 방지하기 위해서 애초에 html태그를 워드프레스 블록 편집으로 모두 변환하여 포스팅되도록 변경하는게 낫겠다는 판단이 들었다.

워드프레스 블록 태그

워드프레스 블록들은 각 블록마다 일정한 형태의 html 태그를 가지고 있다.

이 블록 형식으로 변경하는 수정건들은 직접 코딩하지 않고 모두 커서 AI를 통해 진행됐다.

한번에 완전한 수정을 해낸 것은 아니고 잘 못 동작하는 부분을 프롬프트를 통해 계속 수정 요청을 하고, 코드에서 잘 못된 부분은 좀 더 세밀하게 수정 조건들을 조절하면서 요청을 통해 수정하였다.

수정된 코드들


abstract-wp-client.ts의 tryToPublish 함수

기존 코드
private async tryToPublish( params : {  
    postParams : WordPressPostParams, auth : WordPressAuthParams, updateMatterData? : ( matter : MatterData ) => void,  
} ) : Promise<WordPressClientResult<WordPressPublishResult>>  
{  
    const { postParams, auth, updateMatterData } = params;  
    const tagTerms = await this.getTags( postParams.tags, auth );  
    postParams.tags = tagTerms.map( term => term.id );  
    
    await this.updatePostImages( {  
        auth, postParams  
    } );  
    
    const html = AppState.markdownParser.render( postParams.content );  
    const result = await this.publish( postParams.title ?? "A post from Obsidian!", html, postParams, auth );
TypeScript
수정 코드
private async tryToPublish( params : {  
    postParams : WordPressPostParams, auth : WordPressAuthParams, updateMatterData? : ( matter : MatterData ) => void,  
} ) : Promise<WordPressClientResult<WordPressPublishResult>>  
{  
    const { postParams, auth, updateMatterData } = params;  
    const tagTerms = await this.getTags( postParams.tags, auth );  
    postParams.tags = tagTerms.map( term => term.id );  
    
    await this.updatePostImages( {  
        auth, postParams  
    } );  
    
    const html = AppState.markdownParser.render( postParams.content );  
	
	// HTML을 워드프레스 블록으로 변환  
	const blockHtml = this.convertToWordPressBlocks( html );

    const result = await this.publish( postParams.title ?? "A post from Obsidian!", blockHtml, postParams, auth );
TypeScript

마크다운 형식의 옵시디언 본문을 html 태그로 변환하고 이 내용으로 포스팅 했던 기존 코드에서 html 태그로 변환후 워드프레스 블록태그로 변환을 한번 더 해준다. 그리고 최종 변환된 내용을 포스팅한다. 사실 마크다운 형식의 내용을 바로 워드프레스 블록 태그로 변환하는게 좀 더 나아보이긴 한다.

이건 나중에 시간과 흥미가 생길 때 한 번 보는 것도 괜찮을 것 같다.

abstract-wp-client.ts의 convertToWordPressBlocks 함수

이 함수는 html태그를 워드프레스 블록 태그로 변환하는 함수이다. 우선 주어진 html태그를 정규식을 이용해 변환할 수 있는 블록 타입으로 구분을 하여 쪼갠다. 여기에서 추가된 코드는 모두 포함시킬 수 없어서 대표로 제목 태그 변경부분만 가지고 설명을 한다.

예시 ) 제목 형식의 html태그를 찾아 워드프레스 블록 태그로 변경
// 제목 태그 처리  
this.collectMatches( html, /<h([1-6])>([\s\S]*?)<\/h\1>/g, ( match ) =>  
{  
    const level     = match[ 1 ];  
    const content   = match[ 2 ];  
    const levelAttr = level !== "2" ? ` {"level":${ level }}` : "";  
  
    allMatches.push  
    ( {  
        type       : "heading",   
        content    : `<h${ level }>${ content }</h${ level }>`,   
        attributes : levelAttr,   
        index      : match.index,   
        length     : match[ 0 ].length,   
        original   : match[ 0 ]  
    } );  
} );
TypeScript

위 코드는 <h1>제목</h1>, <h2>제목</h2> 와 같은 제목 태그를 찾아 워드프레스 블록 태그로 변경한다. 바로 워드프레스 블록 태그로 전환되는 것은 아니고 워드프레스 블록 태그로 전환될 수 있는 인터페이스 형태로 수집 후 나중에 일괄 처리된다.

인터페이스는 다음과 같다.

Match 인터페이스
interface Match  
{  
    type        : string;  
    content     : string;  
    attributes? : string;  
    index       : number;  
    length      : number;  
    original    : string;  
}
TypeScript

이 Match 인터페이스는 다음과 같은 워드프레스 블록 태그를 생성한다.

<!-- wp:${type} ${attribute} -->
${content}
<!-- /wp:${type} -->
HTML

제목 태그는 다음과 같이 생성되는 것이다.

<!-- wp:heading -->
<h1 class="wp-block-heading">제목</h1>
<!-- /wp:heading -->
HTML

이런식으로 워드프레스에서 제공하는 여러 형태의 블록 태그로 전환된다. 이 수정건을 적용해서 플러그인을 업데이트한 후 테스트로 포스팅을 해보니 기존에는 클래식 편집기로 진입했던 부분이 바로 블록 편집기로 진입하는 것을 확인할 수 있었다. 이제 내 입맛대로 레이아웃을 적용하여 포스팅할 수 있는 환경이 마련된 것 같다.

블록 편집 예시

바로 블록 편집모드로 편집을 시작할 수 있다

0 답글

댓글을 남겨주세요

Want to join the discussion?
Feel free to contribute!

답글 남기기

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