在WordPress中创建自定义字段,你可以按照以下步骤进行。这里是一个示例代码,你可以根据需要进行修改。
步骤1: 打开你的主题文件(通常是functions.php
),添加以下代码:
function add_custom_meta_box() {
add_meta_box(
'custom_meta_box', // 自定义字段标识符
'自定义字段', // 自定义字段标题
'show_custom_meta_box', // 显示自定义字段的回调函数
'post', // 可以更改要显示自定义字段的文章类型
'normal', // 自定义字段框的位置(normal、advanced、side)
'high' // 自定义字段框的优先级(high、core、default、low)
);
}
add_action('add_meta_boxes', 'add_custom_meta_box');
function show_custom_meta_box() {
global $post;
$custom_field = get_post_meta($post->ID, 'custom_field', true);
?>
<label for="custom_field">自定义字段:</label>
<input type="text" id="custom_field" name="custom_field" value="<?php echo esc_attr($custom_field); ?>">
<?php
}
function save_custom_meta_box($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']));
}
}
add_action('save_post', 'save_custom_meta_box');
步骤2: 保存functions.php
文件,并刷新你的网站。
现在,你的WordPress中就创建了一个名为"自定义字段"的字段。你可以在文章编辑页面中找到它。