首页 问答 正文

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

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

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

  1. functions.php文件中使用add_meta_box()函数来添加自定义字段和元数据的显示区块。示例代码如下:
function custom_meta_box() {
    add_meta_box(
        'my_meta_box',
        '自定义字段',
        'display_custom_meta_box',
        'post',
        'normal',
        'default'
    );
}
add_action( 'add_meta_boxes', 'custom_meta_box' );

function display_custom_meta_box( $post ) {
    $value = 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( $value ); ?>">
    <?php
}

function save_custom_meta_box( $post_id ) {
    if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
        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' ); 
  1. 上述代码中,add_meta_box()函数创建了一个名为my_meta_box的自定义字段显示区块,该区块添加在“文章”(post)编辑页面的“常规”(normal)位置位置,默认优先级。你可以根据需要进行修改。

  2. display_custom_meta_box()函数用于在自定义字段显示区块中输出字段的HTML代码,并通过get_post_meta()函数获取字段的值。

  3. save_custom_meta_box()函数用于保存字段的值,通过update_post_meta()函数更新元数据。

  4. 以上代码中的自定义字段名为_custom_field,你可以根据实际需求进行修改。

  5. 使用以上代码后,你将在文章编辑页面的“常规”区块中看到一个名为“自定义字段”的输入框,你可以在其中输入你想要的值,并保存文章。这样,在显示文章时,你可以通过get_post_meta()函数来获取并显示自定义字段的值。

请注意,以上代码为示例代码,仅供参考。根据实际需求进行相应的修改和调整。

大家谈论
    我的见解