워드프레스 3.4버젼 이후로 테마의 각종 스타일을 편리하게 변경하는 customizer(사용자 정의하기) 기능이 추가 되었죠. customizer는 사용자가 직접 스타일의 변경을 눈으로 확인하고 마음에 드는 설정을 저장할 수 있는 장점이 있습니다. 이번 포스트에서는 customizer에 대해 자세히 알아보도록 하겠습니다.
Customizer란
The Theme Customization API, added in WordPress 3.4, allows developers to customize and add controls to the “Appearance” → “Customize” admin screen. The Theme Customization screen (i.e. “Theme Customizer”) allows site admins to tweak a theme’s settings, color scheme or widgets, and see a preview of those changes in real time. Theme Customization API
실시간으로 테마의 변경사항을 보면서 각종 스타일 설정 등을 할 수 있는 기능입니다. 아래 스크린 캡춰를 보시면 제가 twenty fourteen 기본 테마에 예시로 만들어본 Top bar color 옵션이 있습니다. 옵션에서 색상을 변경하면 자동으로 지정된 영역의 색상이 변경됩니다.
테마의 customizer에 정의되지 않은 스타일 찾기
먼저 사용하시는 테마의 customizer에 정의되어 있지 않은 스타일 중에서 자주 변경이 필요한 부분을 선택해서 customizer에 추가해야겠죠. 저는 twenty fourteen에서 top bar가 검정색이라 왠지 전체적으로 어두운 느낌이 들어서 이 부분(.site-header
)을 customizer에 추가해보기로 했습니다. 브라우져의 개발자 도구(예: 크롬 개발자 도구)를 열어서 변경하고자 하는 영역을 찾고 그 영역에 사용된 class를 사용해보세요.
Customizer 기능 functions.php에 추가
Codex에 있는 Sample Theme Customization Class를 참고하여 자식테마의 functions.php에 아래와 같은 코드를 삽입합니다. 간단히 아래의 클래스를 설명해보면 다음과 같습니다.
- 1. 추가할 설정을 register를 통해 customizer로 등록합니다.
- — add_section: customizer에서 비슷한 설정들을 그룹으로 지정해서 해당 영역에 표시합니다.(예: HwangC Options )
- — add_setting: 추가하고자 하는 설정입니다.(아래 코드에서는
top_bar_color
id에 사용자가 지정한 값이 저장됩니다.) - — add_control: add_section에 위의 add_setting을 연결하고 customizer에 사용자가 사용할 설정 폼을 표시합니다.
- 2. 사용자가 live_preview에 등록한 javascript를 이용해 실시간으로 변경되는 화면을 확인합니다.
- 3. 원하는 스타일을 선택 후 header_output에서 head 영역에 추가합니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 |
<?php /** * Contains methods for customizing the theme customization screen. * * @link http://codex.wordpress.org/Theme_Customization_API * @since HwangC 1.0 */ class HwangC_Customize { /** * This hooks into 'customize_register' (available as of WP 3.4) and allows * you to add new sections and controls to the Theme Customize screen. * * Note: To enable instant preview, we have to actually write a bit of custom * javascript. See live_preview() for more. * * @see add_action('customize_register',$func) * @param \WP_Customize_Manager $wp_customize * @link http://hwangc.com * @since HwangC 1.0 */ public static function register ( $wp_customize ) { //1. Define a new section (if desired) to the Theme Customizer $wp_customize->add_section( 'hwangc_options', array( 'title' => __( 'HwangC Options', 'hwangc' ), //Visible title of section 'priority' => 35, //Determines what order this appears in 'capability' => 'edit_theme_options', //Capability needed to tweak 'description' => __('Allows you to customize colors.', 'hwangc'), //Descriptive tooltip ) ); //2. Register new settings to the WP database... $wp_customize->add_setting( 'top_bar_color', //No need to use a SERIALIZED name, as `theme_mod` settings already live under one db record array( 'default' => '#000', //Default setting/value to save 'type' => 'theme_mod', //Is this an 'option' or a 'theme_mod'? 'capability' => 'edit_theme_options', //Optional. Special permissions for accessing this setting. 'transport' => 'postMessage', //What triggers a refresh of the setting? 'refresh' or 'postMessage' (instant)? ) ); //3. Finally, we define the control itself (which links a setting to a section and renders the HTML controls)... $wp_customize->add_control( new WP_Customize_Color_Control( //Instantiate the color control class $wp_customize, //Pass the $wp_customize object (required) 'hwangc_top_bar_color', //Set a unique ID for the control array( 'label' => __( 'Top Bar Color', 'hwangc' ), //Admin-visible name of the control 'section' => 'hwangc_options', //ID of the section this control should render in (can be one of yours, or a WordPress default section) 'settings' => 'top_bar_color', //Which setting to load and manipulate (serialized is okay) 'priority' => 10, //Determines the order this control appears in for the specified section ) ) ); } /** * This will output the custom WordPress settings to the live theme's WP head. * * Used by hook: 'wp_head' * * @see add_action('wp_head',$func) * @since HwangC 1.0 */ public static function header_output() { ?> <!--Customizer CSS--> <style type="text/css"> <?php self::generate_css('.site-header', 'background-color', 'top_bar_color' ); ?> </style> <!--/Customizer CSS--> <?php } /** * This outputs the javascript needed to automate the live settings preview. * Also keep in mind that this function isn't necessary unless your settings * are using 'transport'=>'postMessage' instead of the default 'transport' * => 'refresh' * * Used by hook: 'customize_preview_init' * * @see add_action('customize_preview_init',$func) * @since HwangC 1.0 */ public static function live_preview() { wp_enqueue_script( 'hwangc-themecustomizer', // Give the script a unique ID get_stylesheet_directory_uri() . '/js/theme-customizer.js', // Define the path to the JS file array( 'jquery', 'customize-preview' ), // Define dependencies '', // Define a version (optional) true // Specify whether to put in footer (leave this true) ); } /** * This will generate a line of CSS for use in header output. If the setting * ($mod_name) has no defined value, the CSS will not be output. * * @uses get_theme_mod() * @param string $selector CSS selector * @param string $style The name of the CSS *property* to modify * @param string $mod_name The name of the 'theme_mod' option to fetch * @param string $prefix Optional. Anything that needs to be output before the CSS property * @param string $postfix Optional. Anything that needs to be output after the CSS property * @param bool $echo Optional. Whether to print directly to the page (default: true). * @return string Returns a single line of CSS with selectors and a property. * @since HwangC 1.0 */ public static function generate_css( $selector, $style, $mod_name, $prefix='', $postfix='', $echo=true ) { $return = ''; $mod = get_theme_mod($mod_name); if ( ! empty( $mod ) ) { $return = sprintf('%s { %s:%s; }', $selector, $style, $prefix.$mod.$postfix ); if ( $echo ) { echo $return; } } return $return; } } // Setup the Theme Customizer settings and controls... add_action( 'customize_register' , array( 'HwangC_Customize' , 'register' ) ); // Output custom CSS to live site add_action( 'wp_head' , array( 'HwangC_Customize' , 'header_output' ) ); // Enqueue live preview javascript in Theme Customizer admin screen add_action( 'customize_preview_init' , array( 'HwangC_Customize' , 'live_preview' ) ); |
js파일 만들기
위에서 기본적인 customizer에 대해 정의를 했다면 live preview가 가능하도록 js파일을 만들어야합니다. js파일은 이미 live_preview()에서 wp_enqueue_script
를 사용해서 등록해두었습니다. 실제 파일을 해당 경로(위의 예: 자식테마폴더/js/theme-customizer.js)에 만들고 아래 코드를 파일에 추가합니다.
아래코드는 위에서 설정한 top_bar_color
를 변경하고자 하는 영역 .site-header
에 실시간으로 적용해서 변경사항을 보면서 설정을 할 수 있도록 도와줍니다.
1 2 3 4 5 6 7 8 9 10 |
( function( $ ) { //Update site top nav bar color in real time... wp.customize( 'top_bar_color', function( value ) { value.bind( function( newval ) { $('.site-header').css('background-color', newval); } ); } ); } )( jQuery ); |
코딩이 어려운 경우에는 플러그인 활용
프리미엄 테마는 보통 설정에 다양한 색상 변경 옵션이 있지만 기본 테마나 무료 테마에는 이런 기능들이 없는 경우가 많습니다. 감사하게도 twenty fourteen은 다양한 색상 변경이 가능한 플러그인이 있네요. 아래 플러그인을 참고해보세요.
마치며
Customizer를 추가하는 방법은 조금 까다로워 보이지만 한번 추가해보시면 다음에는 조금 더 쉽게 원하는 설정을 추가하실 수 있을 것 같네요. 여러분의 테마에 원하는 설정을 Customizer에 추가하여 편리하게 테마를 꾸며보세요. 그럼 오늘도 즐거운 블로깅 하세요!
글과 관련은 없지만 궁금한점이 있어서 글써봅니다.
포트폴리오 페이지에서 카테고리를 나눌때 순서를 바꿀순없는건가요?
abc순으로 무조건 나뉘어져서요