首页 问答 正文

如何为WordPress主题添加自定义字段?

注册会员 / 悠然自学 / 2023-06-12/ 浏览 145 次

WordPress主题可以通过添加自定义字段来拓展文章类型的元数据(metadata),比如文章作者(author)、文章来源(source)、发布日期(published date)等。下面是添加自定义字段的步骤:

  1. 打开主题的functions.php文件,用下面的代码创建一个自定义字段:
// Replace 'custom_field_name' with desired field name
function add_custom_meta_box() {
    add_meta_box(
        'custom_meta_box', // meta box ID
        'Custom Field Name', // title
        'show_custom_meta_box' // callback function
    );
}

function show_custom_meta_box() {
    global $post;
    $meta = get_post_meta( $post->ID, 'custom_field_name', true ); // Replace 'custom_field_name' with desired field name
    ?>
    <input type="text" name="custom_field_name" value="<?php echo $meta; ?>">
    <?php
}

add_action( 'add_meta_boxes', 'add_custom_meta_box' ); 
  1. 保存并激活主题。此时在文章编辑页面下方会出现一个“Custom Field Name”字段,可以输入内容并保存。

  2. 在主题模板中显示自定义字段的内容,可以使用下面的代码在任何需要的地方输出自定义字段的值:

// Replace 'custom_field_name' with desired field name
$meta = get_post_meta( $post->ID, 'custom_field_name', true ); 
echo $meta; 

注意:自定义字段的名称需要根据需要自行定义,并且要确保唯一性。

大家谈论
    我的见解