일반 설정 페이지에 여러 사용자 정의 필드 추가


22

내가하고 싶은 것은 일반 설정에 몇 가지 사용자 정의 필드를 추가하는 것입니다. 이것은 내가 사용하는 코드입니다. 그것은 잘 작동하지만 더 많은 필드를 추가하는 방법을 알 수 없습니다.

전화 번호와 주소에 대한 두 개의 필드를 작성하려고합니다.

function register_fields()
{
    register_setting('general', 'my_first_field', 'esc_attr');
    add_settings_field('my_first_field', '<label for="my_first_field">'.__('My Field' , 'my_first_field' ).'</label>' , 'print_custom_field', 'general');
}

function print_custom_field()
{
    $value = get_option( 'my_first_field', '' );
    echo '<input type="text" id="my_first_field" name="my_first_field" value="' . $value . '" />';
}

add_filter('admin_init', 'register_fields');

여러 필드에서 작동하도록하는 유일한 방법은 모든 것을 복제하는 것입니다.

그러면 다음과 같이 보일 것입니다.

function register_fields()
{
    register_setting('general', 'my_first_field', 'esc_attr');
    add_settings_field('my_first_field', '<label for="my_first_field">'.__('My Field' , 'my_first_field' ).'</label>' , 'print_first_field', 'general');

    register_setting('general', 'my_second_field', 'esc_attr');
    add_settings_field('my_second_field', '<label for="my_second_field">'.__('My Field' , 'my_second_field' ).'</label>' , 'print_second_field', 'general');
}

function print_first_field()
{
    $value = get_option( 'my_first_field', '' );
    echo '<input type="text" id="my_first_field" name="my_first_field" value="' . $value . '" />';
}

function print_second_field()
{
    $value = get_option( 'my_second_field', '' );
    echo '<input type="text" id="my_second_field" name="my_second_field" value="' . $value . '" />';
}

add_filter('admin_init', 'register_fields');

그러나 이것은 아마도 그것을하는 가장 좋은 방법은 settings_section아니지만 , 나는 그것을 만들려고 시도했지만 작동하지 않거나 저장하지 않았습니다. 매우 혼란 스럽습니다.

답변:


26

두 번째 코드는 기술적으로 올바른 방법입니다. 그러나, add_settings_field()당신은 말다툼을 통과 할 수 있습니다.

보기 바랍니다 워드 프레스 Add_Settings_Field의 함수 참조. 이렇게하면 add_settings_field()함수의 실제 작동 방식을 최대한 이해하는 데 도움이됩니다 .

이제 말했듯이 콜백에 '공유' 기능을 사용할 수 있습니다 . 테마를 개발할 때 옵션 페이지에서와 같이.

내가하는 방법의 예는 다음과 같습니다.

// My Example Fields
add_settings_field(  
    'tutorial_display_count',                      
    'Tutorial Display Count',               
    'ch_essentials_textbox_callback',   
    'ch_essentials_front_page_option',                     
    'ch_essentials_front_page',
    array(
        'tutorial_display_count' // $args for callback
    ) 
);
add_settings_field(  
    'blog_display_count',                      
    'Blog Display Count',               
    'ch_essentials_textbox_callback',   
    'ch_essentials_front_page_option',                     
    'ch_essentials_front_page',
    array(
        'blog_display_count'  // $args for callback
    ) 
);

// My Shared Callback
function ch_essentials_textbox_callback($args) { 

$options = get_option('ch_essentials_front_page_option'); 

echo '<input type="text" id="'  . $args[0] . '" name="ch_essentials_front_page_option['  . $args[0] . ']" value="' . $options[''  . $args[0] . ''] . '"></input>';

}

필요에 맞게 약간의 사용자 정의가 필요하지만 콜백에 대해 공유 기능을 수행하면 코드 측면에서 많은 공간이 절약됩니다. 그 외에는 그대로 올바르게 수행하고 있습니다.

--편집하다--

좋아, 이것은 당신에게 좋을 것입니다. 필요에 따라 코드를 수정하고, 나는 이것을 즉시 작성했습니다. 필요에 맞게을 수정하기 만하면 add_settings_field됩니다. 더 추가해야하는 경우 복사하여 붙여 넣기 만하면됩니다. 에 있는지 확인 register_setting하거나 작동하지 않습니다.

add_action('admin_init', 'my_general_section');  
function my_general_section() {  
    add_settings_section(  
        'my_settings_section', // Section ID 
        'My Options Title', // Section Title
        'my_section_options_callback', // Callback
        'general' // What Page?  This makes the section show up on the General Settings Page
    );

    add_settings_field( // Option 1
        'option_1', // Option ID
        'Option 1', // Label
        'my_textbox_callback', // !important - This is where the args go!
        'general', // Page it will be displayed (General Settings)
        'my_settings_section', // Name of our section
        array( // The $args
            'option_1' // Should match Option ID
        )  
    ); 

    add_settings_field( // Option 2
        'option_2', // Option ID
        'Option 2', // Label
        'my_textbox_callback', // !important - This is where the args go!
        'general', // Page it will be displayed
        'my_settings_section', // Name of our section (General Settings)
        array( // The $args
            'option_2' // Should match Option ID
        )  
    ); 

    register_setting('general','option_1', 'esc_attr');
    register_setting('general','option_2', 'esc_attr');
}

function my_section_options_callback() { // Section Callback
    echo '<p>A little message on editing info</p>';  
}

function my_textbox_callback($args) {  // Textbox Callback
    $option = get_option($args[0]);
    echo '<input type="text" id="'. $args[0] .'" name="'. $args[0] .'" value="' . $option . '" />';
}

그래서 내가 이해하지 못하는 것은 add_settings_field ()의 4 번째와 5 번째 매개 변수입니다. 첫 번째는 ID, 두 번째는 이름, 세 번째는 그것을 표시하는 콜백이라는 것을 알고 있지만 다음은 무엇입니까? 둘 다에 대해 ch_essentials_front_page_option이 있습니다. 동일한 위치에 '일반'이 있습니다. 다음은 비어 있고 마지막은 이제 args 배열입니다. 이제 콜백에는 해당 값을 가진 get_option이 있지만 내 경우에 무엇을 넣을 지 모르겠습니다.
— Richard Mišenčík

2
편집은 100 % 진행될 것입니다. 문제 나 궁금한 점이 있으면 알려주세요. 나는 그것을 크게 언급했다.
— MrJustin은

@MrJusting 감사합니다. 실제로 프로필을보고 "사용자 정의 메뉴 페이지의 구현 탭 탭"에 대한 질문을 확인하여 문제가 해결되었습니다. 주석이 잘 달렸으므로 코드를 비교하고 작동 방식을 마침내 이해했습니다. 나에게 페이지와 섹션 매개 변수가 혼란 스럽지만 설정 섹션이 아니라 페이지 섹션과 비슷했지만 이제 두 개를 결합하여 $ args에 다른 값을 추가했습니다. 첫 번째는 필드 id이고 두 번째는 description이며, args [1] :)를 사용하여 설명을 에코하는 콜백 함수에 다른 행을 추가했습니다.
— Richard Mišenčík

궁금한 점이 있으면 알려주세요.
— MrJustin

나는 지금 별도의 메뉴 페이지를 만들고 거기에 옵션을 추가하려고 노력할 것입니다. 어떻게했는지 알려 드리겠습니다
— Richard Mišenčík

0

더 좋은 방법은 워드 프레스 옵션 플러그인을 사용하는 것입니다. 최고 중 하나는 고급 사용자 정의 필드입니다.

http://www.advancedcustomfields.com/

옵션 페이지 애드온을 구입하면 많은 기능을 갖춘 무제한 옵션 페이지를 만들 수 있습니다. 비디오를 봐주세요.

http://www.advancedcustomfields.com/add-ons/options-page/

매우 유용한 플러그인과 애드온.


3
나는 단지 몇 개의 필드를 추가하고 싶기 때문에 이것에 대한 플러그인은 나를 위해 과잉 일 것이지만 감사합니다.
— Richard Mišenčík

8
말할 것도없이 OP가 원하는 것을 해결하지 못했습니다. 일반 설정에 필드를 추가하는 것이 었습니다. AFAIK, ACF에서는 일반 설정에 필드를 추가 할 수 없습니다.
— NW Tech
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.