데브포일 홈
WordPress 자동화
Guest
STAGE 13 · Lv.63

숏코드와 블록 제작

add_shortcode로 숏코드를 만들고, block.json과 React 기반의 구텐베르크 블록을 제작합니다. InnerBlocks, 블록 컨트롤, 동적 블록까지 학습합니다.

숏코드(Shortcode)의 세계

숏코드란?

숏코드는 대괄호 안에 키워드를 넣어 복잡한 기능을 간단하게 삽입하는 WordPress의 매크로 시스템입니다. [gallery], [audio], [video] 등이 WordPress 내장 숏코드입니다. 플러그인 개발자는 커스텀 숏코드를 만들어 사용자가 어디서든 특정 기능을 쉽게 사용할 수 있게 합니다.


구텐베르크 블록 에디터가 도입된 이후에도 숏코드는 여전히 유효합니다. 클래식 에디터 사용자, 위젯 영역, 텍스트 필드 등에서 숏코드가 필요하며, 블록으로 전환하기 어려운 레거시 기능에도 사용됩니다.

📝
Self-closing
[shortcode attr="val"]
📦
Enclosing
[shortcode]내용[/shortcode]

add_shortcode() 기본 사용법

// 기본 숏코드 등록 add_shortcode('greeting', function($atts, $content = null) { // 기본 속성값 설정 $atts = shortcode_atts([ 'name' => '방문자', 'color' => '#333', ], $atts, 'greeting'); // 3번째 인자: 숏코드 이름 (필터 지원) return sprintf( '<p style="color:%s">안녕하세요, %s님!</p>', esc_attr($atts['color']), esc_html($atts['name']) ); }); // 사용: [greeting name="홍길동" color="#ff0000"] // 출력: <p style="color:#ff0000">안녕하세요, 홍길동님!</p>
// Enclosing 숏코드 (감싸는 형태) add_shortcode('highlight', function($atts, $content = null) { $atts = shortcode_atts([ 'bg' => '#ffeb3b', ], $atts); // do_shortcode(): 내부 숏코드도 처리 $inner = do_shortcode($content); return sprintf( '<span style="background:%s;padding:2px 6px">%s</span>', esc_attr($atts['bg']), wp_kses_post($inner) ); }); // 사용: [highlight bg="#00ff00"]중요한 텍스트[/highlight]
숏코드 개발 시 주의사항
1. echo가 아닌 return 사용: 숏코드 콜백은 반드시 문자열을 반환해야 합니다. echo를 사용하면 출력 순서가 꼬입니다.

2. 출력 버퍼링: 복잡한 HTML을 반환할 때는 ob_start()/ob_get_clean()을 사용하세요.

3. 이스케이프: 사용자 입력 속성값은 반드시 esc_attr(), esc_html()로 이스케이프합니다.

4. 중첩 주의: 같은 숏코드를 중첩하면 파싱 오류가 발생할 수 있습니다.
// 실전 예제: 최근 글 목록 숏코드 add_shortcode('recent_posts', function($atts) { $atts = shortcode_atts([ 'count' => 5, 'category' => '', 'orderby' => 'date', 'style' => 'list', ], $atts); $query_args = [ 'post_type' => 'post', 'posts_per_page' => absint($atts['count']), 'orderby' => sanitize_text_field($atts['orderby']), 'order' => 'DESC', ]; if (!empty($atts['category'])) { $query_args['category_name'] = sanitize_text_field($atts['category']); } $posts = new WP_Query($query_args); if (!$posts->have_posts()) { return '<p>표시할 글이 없습니다.</p>'; } ob_start(); ?> <ul class="map-recent-posts map-style-<?php echo esc_attr($atts['style']); ?>"> <?php while ($posts->have_posts()) : $posts->the_post(); ?> <li> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <span class="date"><?php echo get_the_date(); ?></span> </li> <?php endwhile; ?> </ul> <?php wp_reset_postdata(); return ob_get_clean(); }); // 사용: [recent_posts count="3" category="news" style="card"]
🔒
여기까지는 미리보기입니다
숏코드와 블록 제작
무료 가입하면 이어서 볼 수 있고, 강의를 완료할 때마다 XP와 레벨이 쌓입니다.
Google로 3초 만에 시작 →🧵 Threads로 시작무료 공개 강의 둘러보기 (Lv.1~3)