問題描述

我想在 Page Attribute 框中新增選擇列表,您可以在頁面的管理介面的右側看到。

有人知道這是否可行?

或至少在此框下方新增自定義框?

最佳解決方案

沒有方便的鉤子來新增東西給那個盒子。

你可以做兩件事之一。

1. 新增一個新的元框

您可以透過掛接到 add_meta_boxes 操作並呼叫 add_meta_box 來執行此操作。您可以在呼叫 add_meta_box 時指定回撥函式。該回撥將照顧回顯您的選擇列表。

<?php
add_action( 'add_meta_boxes', 'wpse44966_add_meta_box' );
/**
 * Adds the meta box to the page screen
 */
function wpse44966_add_meta_box()
{
    add_meta_box(
        'wpse44966-meta-box', // id, used as the html id att
        __( 'WPSE 44966 Meta Box' ), // meta box title, like "Page Attributes"
        'wpse44966_meta_box_cb', // callback function, spits out the content
        'page', // post type or page. We'll add this to pages only
        'side', // context (where on the screen
        'low' // priority, where should this go in the context?
    );
}

/**
 * Callback function for our meta box.  Echos out the content
 */
function wpse44966_meta_box_cb( $post )
{
    // create your dropdown here
}

2. 刪除預設頁面屬性元框,新增您自己的版本

帖子編輯螢幕上的所有內容,除主編輯器和標題區域外,都是一個元框。您可以透過呼叫 remove_meta_box 刪除它們,然後將其替換為您自己的。

所以,首先,修改上面的 add 函式以包括一個刪除元框呼叫。然後,您需要從 wp-admin/includes/meta-boxes.php 複製 page_attributes_meta_box 功能體,並將其放在下面。

<?php
add_action( 'add_meta_boxes', 'wpse44966_add_meta_box' );
/**
 * Adds the meta box to the page screen
 */
function wpse44966_add_meta_box( $post_type )
{
    // remove the default
    remove_meta_box(
        'pageparentdiv',
        'page',
        'side'
    );

    // add our own
    add_meta_box(
        'wpse44966-meta-box',
        'page' == $post_type ? __('Page Attributes') : __('Attributes'),
        'wpse44966_meta_box_cb', 
        'page', 
        'side', 
        'low'
    );
}

/**
 * Callback function for our meta box.  Echos out the content
 */
function wpse44966_meta_box_cb( $post )
{
    // Copy the the `page_attributes_meta_box` function content here
    // add your drop down
}

無論哪種方式,您都需要掛接到 save_post,以使用 add_post_meta 和/或 update_post_meta 來儲存欄位的值。

<?php
add_action( 'save_post', 'wpse44966_save_post' );
/**
 * Save our custom field value
 */
function wpse44966_save_post( $post_id )
{
    // check nonces, permissions here
    // save the data with update_post_meta
}

This tutorial 可能會幫助您。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。