在WordPress中,您可以使用自定義字段(Custom Fields)或稱為元數(shù)據(jù)(Meta Data)來為特定分類目錄下的內(nèi)容添加額外的信息。自定義字段可以附加到文章、頁面、用戶和其他對象上。以下是一個逐步指南,介紹如何為特定分類目錄下的內(nèi)容添加自定義字段,并在內(nèi)容錄入時顯示這些字段。
步驟 1: 添加自定義字段
首先,您需要在WordPress后臺創(chuàng)建一個自定義字段。這可以通過在主題函數(shù)文件(functions.php)中添加代碼來實現(xiàn)。
打開您的WordPress主題文件夾,并找到functions.php文件。
在functions.php文件中添加以下代碼,以創(chuàng)建一個名為my_custom_field的自定義字段,并將其與特定分類關(guān)聯(lián):
// 添加自定義字段
function add_custom_field_to_category() {
register_meta('post', 'my_custom_field', array(
'type' => 'text',
'single' => true,
'show_in_rest' => true,
'label' => '我的自定義字段',
'description' => '這是一個自定義字段示例。',
));
}
add_action('init', 'add_custom_field_to_category');
// 將自定義字段與特定分類關(guān)聯(lián)
function load_custom_field_for_category($term) {
$term_id = $term->term_id;
$category_name = $term->name;
// 假設(shè)您的分類名稱是 "特定分類"
if ($category_name === '特定分類') {
add_meta_box(
'my_custom_field_box',
'我的自定義字段',
'display_custom_field_box',
'post',
'normal',
'high'
);
}
}
add_action('load-post.php', 'load_custom_field_for_category');
add_action('load-post-new.php', 'load_custom_field_for_category');
// 顯示自定義字段的輸入框
function display_custom_field_box() {
global $post;
echo '<input type="text" id="my_custom_field" name="my_custom_field" value="' . get_post_meta($post->ID, 'my_custom_field', true) . '" size="30" style="width:97%;" />';
}
請注意,上述代碼中的特定分類應(yīng)替換為您想要添加自定義字段的實際分類名稱。
步驟 2: 保存自定義字段的值
接下來,您需要在WordPress保存文章時保存自定義字段的值。這可以通過添加以下代碼到functions.php文件來實現(xiàn):
// 保存自定義字段的值
function save_custom_field_value($post_id) {
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
if (!current_user_can('edit_post', $post_id)) {
return;
}
if (isset($_POST['my_custom_field'])) {
update_post_meta($post_id, 'my_custom_field', $_POST['my_custom_field']);
} else {
delete_post_meta($post_id, 'my_custom_field');
}
}
add_action('save_post', 'save_custom_field_value');
步驟 3: 在內(nèi)容錄入時顯示自定義字段
最后,您可以在文章編輯頁面和內(nèi)容頁面顯示自定義字段。這可以通過編輯WordPress的模板文件來實現(xiàn)。
打開您的WordPress主題文件夾,并找到single.php或content.php文件(取決于您的主題結(jié)構(gòu))。
在適當(dāng)?shù)奈恢锰砑右韵麓a,以顯示自定義字段的值:
<?php if (get_post_meta($post->ID, 'my_custom_field', true)) : ?>
<p>我的自定義字段: <?php echo get_post_meta($post->ID, 'my_custom_field', true); ?></p>
<?php endif; ?>
這段代碼會檢查當(dāng)前文章是否有my_custom_field自定義字段,并在有值的情況下顯示它。
完成
現(xiàn)在,當(dāng)您在WordPress后臺為特定分類下的文章添加或編輯內(nèi)容時,應(yīng)該會看到一個名為“我的自定義字段”的新輸入框。您可以在這個輸入框中輸入自定義字段的值,這些值會在保存文章后保存,并在文章頁面上顯示。