首页 问答 正文

如何在WordPress主题中添加自定义字段和元数据?

注册会员 / 悠然自学 / 2023-07-11/ 浏览 132 次

要在WordPress主题中添加自定义字段和元数据,你可以按照以下步骤进行操作:

  1. 在主题目录下创建一个名为functions.php的文件(如果已经存在,请打开这个文件)。

  2. functions.php文件中添加以下代码以创建自定义字段:

add_action('add_meta_boxes', 'custom_meta_box');
add_action('save_post', 'save_custom_meta');

function custom_meta_box() {
    add_meta_box('custom_fields', '自定义字段', 'display_custom_fields', 'post', 'normal', 'high');
}

function display_custom_fields($post) {
    // 获取已保存的自定义字段值
    $custom_field_value = get_post_meta($post->ID, 'custom_field', true);

    // 在编辑页面显示自定义字段的输入框
    echo '<label for="custom_field">自定义字段:</label>';
    echo '<input type="text" id="custom_field" name="custom_field" value="' . esc_attr($custom_field_value) . '">';
}

function save_custom_meta($post_id) {
    // 检查是否是自动保存的数据
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return;
    }

    // 检查用户是否有权限编辑自定义字段
    if (!current_user_can('edit_post', $post_id)) {
        return;
    }

    // 保存自定义字段的值
    if (isset($_POST['custom_field'])) {
        update_post_meta($post_id, 'custom_field', sanitize_text_field($_POST['custom_field']));
    }
} 
  1. 在以上代码中,custom_meta_box函数用于添加一个"自定义字段"的元框,它将在编辑页面上显示。

  2. display_custom_fields函数用于在元框上显示已保存的自定义字段的值,并提供一个输入框供用户更新该值。

  3. save_custom_meta函数用于在保存文章时将用户输入的自定义字段值保存到数据库中。

  4. 保存完functions.php文件后,刷新后台编辑页面,你将会在编辑页面的边栏或下方看到一个名为"自定义字段"的元框。在这里你可以输入自定义字段的值,并保存。

请注意,上述代码中的自定义字段名称为custom_field,你可以根据自己的需求进行更改。

希望以上代码对你有帮助!

大家谈论
    我的见解