浮萍漂泊本无根
天涯游子君莫问

WordPress自定义文章添加自定义字段面板

要在WordPress中为自定义文章类型添加自定义字段面板,您可以使用以下步骤:

创建自定义文章类型: 如果您还没有创建自定义文章类型,您可以使用函数 register_post_type()来创建它。在您的主题的 functions.php 文件中添加类似以下的代码:

function custom_post_type() {
    register_post_type('custom_post', array(
        'labels' => array(
            'name' => '自定义文章',
            'singular_name' => '自定义文章',
        ),
        'public' => true,
        'has_archive' => true,
        'supports' => array('title', 'editor', 'thumbnail', 'customfields'), // 这里包括了customfields
    ));
}
add_action('init', 'custom_post_type');

添加自定义字段: 现在,您需要添加自定义字段。为此,您可以使用 add_post_meta()update_post_meta() 函数。以下是一个示例:

function add_custom_fields_metabox() {
    add_meta_box('custom_fields', '自定义字段', 'display_custom_fields_metabox', 'custom_post', 'normal', 'high');
}

function display_custom_fields_metabox($post) {
    // 在这里添加您的自定义字段表单元素
    $custom_value = get_post_meta($post>ID, '_custom_field_key', true);

    echo '<label for="custom_field">自定义字段:</label>';
    echo '<input type="text" id="custom_field" name="custom_field" value="' . esc_attr($custom_value) . '" />';
}

function save_custom_fields($post_id) {
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) return;

    if (isset($_POST['custom_field'])) {
        update_post_meta($post_id, '_custom_field_key', sanitize_text_field($_POST['custom_field']));
    }
}

add_action('add_meta_boxes', 'add_custom_fields_metabox');
add_action('save_post', 'save_custom_fields');

上述代码会在自定义文章类型的编辑页面上添加一个自定义字段面板,您可以在其中输入自定义字段的值。

显示自定义字段的值: 最后,在您的自定义文章模板中,您可以使用 get_post_meta() 函数来显示自定义字段的值。例如:

$custom_value = get_post_meta(get_the_ID(), '_custom_field_key', true);
echo '自定义字段的值:' . esc_html($custom_value);

这就是为自定义文章类型添加自定义字段面板的基本步骤。您可以根据自己的需求扩展和自定义这些字段。请确保备份您的网站数据,以防不时之需。

赞(0) 打赏
未经允许不得转载:主题秀 » WordPress自定义文章添加自定义字段面板

评论 抢沙发

评论前必须登录!

 

更好的WordPress主题

支持快讯、专题、百度收录推送、人机验证、多级分类筛选器,适用于垂直站点、科技博客、个人站,扁平化设计、简洁白色、超多功能配置、会员中心、直达链接、文章图片弹窗、自动缩略图等...

联系我们联系我们

觉得文章有用就打赏一下文章作者

非常感谢你的打赏,我们将继续提供更多优质内容,让我们一起创建更加美好的网络世界!

支付宝扫一扫

微信扫一扫

登录

找回密码

注册