close

wordpress-3446166_960_720.jpg

(圖片來源)

WordPress 本身的文章管理功能做的已經是相當完善,但需求總是無窮無盡的,比方說想發佈展覽會議活動的文章,那我需要儲存地區、國家、城市、開始時間、結束時間與活動網址等資訊,這就必須要新增自定義的欄位來儲存這些活動相關的資訊,新增自定義欄位有兩種方法。

 

1. 直接使用新增文章的自訂欄位

 

2. 使用語法建立一個自訂欄位

 

我所使用的是第二種方法,我個人比較喜歡可擴充可掌控的感覺,所以撰寫程式碼的方式會讓我比較放心,當然這兩種都有他的特點,有時若只是想簡單的呼叫自訂欄位使用第一種應該比較快,若長期要使用的話,還是建議使用第二種以免太多自訂欄位代碼搞昏了頭。那麼接下來會介紹第二種方式如何實作出自定義的欄位,對於第一種方式感興趣的也可以參考我後面所附上的連結。

 

Step1. 使用語法建立一個自訂欄位

首先要設定自訂欄位的相關參數,先看完下方圖解相關參數所對應的意義,再看程式碼的部分就會更加清楚囉!

 

// 展覽會議的自定義欄位
$event_box = array(
    'id' => 'post-meta-event',
    'title' => '展会资讯',
    'page' => 'post',
    'context' => 'normal',
    'priority' => 'high',
    'fields' => array(
        array(
            'name' => '展会地区',
            'id' => 'field_area',
            'type' => 'select',
            'options' => array('亚洲', '欧洲', '非洲', '北美洲', '南美洲', '大洋洲')
        ),
        array(
            'name' => '展会国家',
            'id' => 'field_country',
            'type' => 'select',
            'options' => getCountry() // 透過自己的 function 從 db 撈取資料
        ),
        array(
            'name' => '展会城市',
            'id' => 'field_city',
            'type' => 'text',
            'std' => '',
            'desc' => ''
        ),
        array(
            'name' => '展会开始日期',
            'id' => 'field_start',
            'type' => 'text',
            'desc' => 'yyyy/mm/dd 例:2015/07/07',
            'std' => ''
        ),
        array(
            'name' => '展会结束日期',
            'id' => 'field_end',
            'type' => 'text',
            'desc' => 'yyyy/mm/dd 例:2015/07/07',
            'std' => ''
        ),
        array(
            'name' => '活动网址',
            'id' => 'field_website',
            'type' => 'text',
            'desc' => '',
            'std' => ''
        )
    )
);

 

Step2. 新增自定義區塊

製作自定義區塊與欄位,並傳入自定義欄位相關參數,其中有使用到 add_meta_box 的 function。

/**
 * 新增自定義區塊
 * @date 2017-08-28T10:11:14+0800
 */
function add_box() {
	global $boxs;

	foreach ($boxs as $key => $box) {
    	add_meta_box($box['id'], $box['title'], 'show_box', $box['page'], $box['context'], $box['priority'], array('box'=>$box));
	}
}
add_action('admin_menu', 'add_box');

 

Step3. 顯示自定義區塊 

顯示該文章相關欄位的資料,這個 function 是搭配 add_meta_box 第 3 個參數。

/**
 * 顯示自定義區塊
 * @param  [type]                   $post [description]
 * @param  [type]                   $box  [description]
 * @return [type]
 * @date   2017-08-28T10:10:53+0800
 */
function show_box($post, $box)
{
    echo '<table class="form-table">';

    foreach ($box['args']['box']['fields'] as $field) {
        // get current post meta data
        $meta = get_post_meta($post->ID, $field['id'], true);

        echo '<tr>',
                '<th style="width:20%"><label for="', $field['id'], '">', $field['name'], '</label></th>',
                '<td>';
        switch ($field['type']) {
            case 'text':
                echo '<input type="text" name="', $field['id'], '" id="', $field['id'], '" value="', $meta ? $meta : $field['std'], '" size="30" style="width:97%" />', '<br />', $field['desc'];
                break;
            case 'textarea':
                echo '<textarea name="', $field['id'], '" id="', $field['id'], '" cols="60" rows="4" style="width:97%">', $meta ? $meta : $field['std'], '</textarea>', '<br />', $field['desc'];
                break;
            case 'select':
                echo '<select name="', $field['id'], '" id="', $field['id'], '">';
                foreach ($field['options'] as $option) {
                    echo '<option', $meta == $option ? ' selected="selected"' : '', '>', $option, '</option>';
                }
                echo '</select>';
                break;
            case 'radio':
                foreach ($field['options'] as $option) {
                    echo '<input type="radio" name="', $field['id'], '" value="', $option['value'], '"', $meta == $option['value'] ? ' checked="checked"' : '', ' />', $option['name'];
                }
                break;
            case 'checkbox':
                echo '<input type="checkbox" name="', $field['id'], '" id="', $field['id'], '"', $meta ? ' checked="checked"' : '', ' />';
                break;
        }
        echo     '<td>',
            '</tr>';
    }

    echo '</table>';
}

 

Step4. 儲存自定義欄位資料

最後要實做新增文章與編輯文章時儲存自定義欄位資料的功能

/**
 * 儲存自定義欄位資料
 * @param  int $post_id 文章ID
 * @date   2017-08-28T10:11:34+0800
 */
function save_data($post_id)
{
    global $boxs;

    // 檢查是否式自動儲存、發文頁面、是否有編輯權限
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return false;
    if (!is_edit_page()) return false;
    if (!current_user_can('edit_post', $post_id)) return false;

    foreach ($boxs as $key => $box) {

        foreach ($box['fields'] as $key => $field) {
            $old = get_post_meta($post_id, $field['id'], true);
            $new = isset($_POST[$field['id']]) ? $_POST[$field['id']] : false;

            if ($new && $new != $old) {
                update_post_meta($post_id, $field['id'], $new);
            } elseif ('' == $new && $old) {
                delete_post_meta($post_id, $field['id'], $old);
            }
        }
    }
}
add_action('save_post', 'save_data');

 

各欄位型態的使用說明:

 

1. Text 範例

array(
    'name' => 'Text box',  //欄位標題
    'desc' => 'Enter something here',  //欄位說明
    'id' => 'text',
    'type' => 'text',
    'std' => 'Default value 1'
)

 

2. Textarea 範例

array(
	'name' => 'Textarea', //欄位標題
	'desc' => 'Enter big text here',  //欄位說明
	'id' => 'textarea', //自訂ID
	'type' => 'textarea',   //型態
	'std' => 'Default value 2'  //預設值
)

 

3. Select 範例

array(
	'name' => 'Select box',      //欄位標題
	'id' => $prefix . 'select',   //自訂ID
	'type' => 'select',               //型態
	'options' => array('Option 1', 'Option 2', 'Option 3')  //參數值
)

 

4. Radio 範例

array(
	'name' => 'Radio',          //欄位標題
	'id' => $prefix . 'radio',    //自訂ID
	'type' => 'radio',    //型態
	'options' => array(
		array('name' => 'Name 1', 'value' => 'Value 1'),    //選項1名稱、參數值
		array('name' => 'Name 2', 'value' => 'Value 2')     //選項2名稱、參數值
	)
)

 

5. Checkbox 範例

array(
	'name' => 'Checkbox', //欄位標題
	'id' => $prefix . 'checkbox',     //自訂ID
	'type' => 'checkbox'  //型態
)

 

參考資料:

如何使用WP自訂欄位
WordPress的自訂區塊(Meta Box)、自訂欄位(Post Meta)及內建自訂欄位元件
developer.wordpress.org add_meta_box

arrow
arrow

    Mayuge 發表在 痞客邦 留言(0) 人氣()