편집기 위의 게시물 편집 페이지의 제목 섹션 아래에 사용자 정의 메타 상자를 배치하려면 어떻게해야합니까?


30

고객이 관리 패널의 제목 / 퍼머 링크 섹션과 게시물 편집기 사이에 배치하려는 사용자 정의 게시물 유형에 대한 사용자 정의 메타 상자가 있습니다. 이것이 가능합니까? 그렇다면 필요한 후크 / 필터 등이 있습니까?


여기에서도 매우 비슷한 질문이 있습니다 : wordpress.stackexchange.com/questions/35416/…
— Simon East

답변:


51
  • 고급 컨텍스트와 높은 우선 순위를 사용하여 메타 박스를 추가하기 만하면됩니다.
  • 그런 다음 edit_form_after_title고리에 걸으십시오
  • 메타 상자를 인쇄 한 다음 제거하여 두 번 나타나지 않도록하십시오.

    // Move all "advanced" metaboxes above the default editor
    add_action('edit_form_after_title', function() {
        global $post, $wp_meta_boxes;
        do_meta_boxes(get_current_screen(), 'advanced', $post);
        unset($wp_meta_boxes[get_post_type($post)]['advanced']);
    });

내가 작업중 인 사이트 register_meta_box_cb는 register_post_type함수 의 매개 변수를 사용하여 일부 메타 박스를 등록 합니다. 코드를 시도했지만 메타 박스가 편집기 위로 이동하지 않습니다. 내 경우에도 사용할 수 있습니까? 감사합니다
— leemon

나는 정의를 사용하는 것이 좋습니다 것 $context대신에, advanced같은 사용 무언가, my_before_editor당신은 모든 메타 박스를 이동하지 않도록, advanced상황, 당신은 특별히 .. 특정 메타 박스를 대상으로 참조 developer.wordpress.org/reference/functions/add_meta_box을
— farinspace을

14

다음은 편집기 위로 특정 메타 박스를 이동하는 방법 이지만 코드를 게시하기 전에 Andrew와 mhulse에게 감사드립니다. 너희들 락!

function foo_deck( $post_type ) {
    if ( in_array( $post_type, array( 'post', 'page' ) ) ) {
        add_meta_box(
            'contact_details_meta',
            'Contact Details',
            'contact_details_meta',
            $post_type,
            'test', // change to something other then normal, advanced or side
            'high'
        );
    }
}

add_action('add_meta_boxes', 'foo_deck');

function foo_move_deck() {
        # Get the globals:
        global $post, $wp_meta_boxes;

        # Output the "advanced" meta boxes:
        do_meta_boxes( get_current_screen(), 'test', $post );

        # Remove the initial "advanced" meta boxes:
        unset($wp_meta_boxes['post']['test']);
    }

add_action('edit_form_after_title', 'foo_move_deck');

1
change to something other then normal, advanced or side-내 경우에는 열쇠였습니다. 정보에 대해서 감사드립니다.
— Mayeenul 이슬람

이것은 나에게 가장 유용한 답변이었습니다. 고맙습니다!
— marvinpoo

12

Andrew의 답변을 기반으로 전체 코드 예제를 제공하려면 ... "Deck"(일명 서브 헤드)을 게시물에 포함시키는 방법이 필요했습니다. 기본 제목 표시 줄 뒤에 데크 필드가 나타나기를 원했습니다.

/**
 * Add a "deck" (aka subhead) meta box to post page(s) and position it
 * under the title.
 *
 * @todo Move to class.
 * @see http://codex.wordpress.org/Function_Reference/add_meta_box
 * @see http://wordpress.org/extend/ideas/topic/add-meta-box-to-multiple-post-types
 * @see https://github.com/Horttcore/WordPress-Subtitle
 * @see http://codex.wordpress.org/Function_Reference/wp_nonce_field
 */

# Adds a box to the main column on the Post and Page edit screens:
function foo_deck($post_type) {

    # Allowed post types to show meta box:
    $post_types = array('post', 'page');

    if (in_array($post_type, $post_types)) {

        # Add a meta box to the administrative interface:
        add_meta_box(
            'foo-deck-meta-box', // HTML 'id' attribute of the edit screen section.
            'Deck',              // Title of the edit screen section, visible to user.
            'foo_deck_meta_box', // Function that prints out the HTML for the edit screen section.
            $post_type,          // The type of Write screen on which to show the edit screen section.
            'advanced',          // The part of the page where the edit screen section should be shown.
            'high'               // The priority within the context where the boxes should show.
        );

    }

}

# Callback that prints the box content:
function foo_deck_meta_box($post) {

    # Use `get_post_meta()` to retrieve an existing value from the database and use the value for the form:
    $deck = get_post_meta($post->ID, '_deck', true);

    # Form field to display:
    ?>

        <label class="screen-reader-text" for="foo_deck">Deck</label>
        <input id="foo_deck" type="text" autocomplete="off" value="<?=esc_attr($deck)?>" name="foo_deck" placeholder="Deck">

    <?php

    # Display the nonce hidden form field:
    wp_nonce_field(
        plugin_basename(__FILE__), // Action name.
        'foo_deck_meta_box'        // Nonce name.
    );

}

/**
 * @see https://wordpress.stackexchange.com/a/16267/32387
 */

# Save our custom data when the post is saved:
function foo_deck_save_postdata($post_id) {

    # Is the current user is authorised to do this action?
    if ((($_POST['post_type'] === 'page') && current_user_can('edit_page', $post_id) || current_user_can('edit_post', $post_id))) { // If it's a page, OR, if it's a post, can the user edit it? 

        # Stop WP from clearing custom fields on autosave:
        if ((( ! defined('DOING_AUTOSAVE')) || ( ! DOING_AUTOSAVE)) && (( ! defined('DOING_AJAX')) || ( ! DOING_AJAX))) {

            # Nonce verification:
            if (wp_verify_nonce($_POST['foo_deck_meta_box'], plugin_basename(__FILE__))) {

                # Get the posted deck:
                $deck = sanitize_text_field($_POST['foo_deck']);

                # Add, update or delete?
                if ($deck !== '') {

                    # Deck exists, so add OR update it:
                    add_post_meta($post_id, '_deck', $deck, true) OR update_post_meta($post_id, '_deck', $deck);

                } else {

                    # Deck empty or removed:
                    delete_post_meta($post_id, '_deck');

                }

            }

        }

    }

}

# Get the deck:
function foo_get_deck($post_id = FALSE) {

    $post_id = ($post_id) ? $post_id : get_the_ID();

    return apply_filters('foo_the_deck', get_post_meta($post_id, '_deck', TRUE));

}

# Display deck (this will feel better when OOP):
function foo_the_deck() {

    echo foo_get_deck(get_the_ID());

}

# Conditional checker:
function foo_has_subtitle($post_id = FALSE) {

    if (foo_get_deck($post_id)) return TRUE;

}

# Define the custom box:
add_action('add_meta_boxes', 'foo_deck');
# Do something with the data entered:
add_action('save_post', 'foo_deck_save_postdata');

/**
 * @see https://wordpress.stackexchange.com/questions/36600
 * @see https://wordpress.stackexchange.com/questions/94530/
 */

# Now move advanced meta boxes after the title:
function foo_move_deck() {

    # Get the globals:
    global $post, $wp_meta_boxes;

    # Output the "advanced" meta boxes:
    do_meta_boxes(get_current_screen(), 'advanced', $post);

    # Remove the initial "advanced" meta boxes:
    unset($wp_meta_boxes['post']['advanced']);

}

add_action('edit_form_after_title', 'foo_move_deck');

분명히 위의 코드는 더 많은 작업을 사용할 수 있지만 다른 사람들이 같은 일을하려고하면 도움이 될 것입니다 (Andrew의 대답은 빛을 발했지만 실제로 실제 예제를 제공하는 것이 도움이 될 것이라고 생각했습니다).

이 답변도 도움이되었습니다 .

개선 사항 :

  1. OOP / 클래스를 만드십시오.
  2. 제목 필드처럼 보이게 / 느끼고 / 동작하도록 스타일 / js를 추가하십시오.

나는 앞으로 어느 시점에서 위의 개선을 할 계획이지만 적어도 위의 코드는 다른 사람들이 이것을 알아 내려고 도울 것입니다.

더 많은 영감을 얻으려면 여기 에서 소스 코드를 참조하십시오 (jQuery를 사용하여 "자막"을 이동하도록 선택했습니다).


누군가가 같은 길을 걷는 데 도움이되는 경우 : 관련 / 유사한 코드가 있는 질문을했습니다 ( "제목"필드를 사용하여 부제목을 필터링하고 선택했습니다).
— mhulse

6

고급 섹션의 모든 것을 맨 위로 이동하는 대신 새 섹션을 만들어 맨 위로 이동하십시오.

// Create 'top' section and move that to the top
add_action('edit_form_after_title', function() {
  global $post, $wp_meta_boxes;
  do_meta_boxes(get_current_screen(), 'top', $post);
  unset($wp_meta_boxes[get_post_type($post)]['top']);
});

이제 top섹션과 high우선 순위를 사용하여 메타 박스를 등록하기 만하면 됩니다.

나를 위해 WordPress 4.4.2에서 작업하고 있습니다. 다른 WP 버전에서는 이것을 테스트하지 않았습니다.


1

편집기를 원하는 위치에 놓을 수있는 다른 방법이 있습니다.

  1. post_type을 등록 할 때 지원 매개 변수에서 편집기를 제거하십시오.

  2. 가짜 메타 박스 추가

    add_meta_box( 'does-not-matter', 
    __( 'Description'), 
    function($post){ 
      wp_editor($post->post_content,'post_content',array('name'=>'post_content'));
    },
    'post_type_type', 
    'advanced', 
    'high' );

참고로, 이것은 여전히 ​​작동하지만 상자를 이동할 때 필드의 내용에 이상한 동작이 발생합니다. 사용자는 조심하십시오.
— Eckstein
당사 사이트를 사용함과 동시에 당사의 쿠키 정책과 개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.