在 WordPress 中将自定义字段添加到自定义帖子类型

use*_*238 0 php wordpress

我创建了几个自定义帖子类型。对于其中之一,我还想添加一个自定义字段。它应该只是一个简单的文本字段,您可以在其中输入一些文本。与标题字段类似。你会怎么做?我不想使用插件。

当前代码(functions.php)

    register_post_type( 'cases',
      array(
        'labels' => array(
            'name' => __( 'Cases' ),
            'singular_name' => __( 'Case' )
        ),
        'publicly_queryable' => true,
        'public' => true,
        'has_archive' => true,
        'rewrite' => array('slug' => 'cases'),
        'supports' => array('title','editor','thumbnail')
      )
    );
Run Code Online (Sandbox Code Playgroud)

dip*_*ala 5

您需要创建自定义元框并在元框中添加该字段。

创建元盒

function add_your_fields_meta_box() {
add_meta_box(
    'your_fields_meta_box', // $id
    'Your Fields', // $title
    'show_your_fields_meta_box', // $callback
    'your_post', // $screen
    'normal', // $context
    'high' // $priority
);
}
add_action( 'add_meta_boxes', 'add_your_fields_meta_box' );
Run Code Online (Sandbox Code Playgroud)

html部分

function show_your_fields_meta_box() {
global $post;  
    $meta = get_post_meta( $post->ID, 'your_fields', true ); ?>

<input type="hidden" name="your_meta_box_nonce" value="<?php echo wp_create_nonce( basename(__FILE__) ); ?>">

<!-- All fields will go here -->

<?php }
Run Code Online (Sandbox Code Playgroud)

将字段保存到数据库中

function save_your_fields_meta( $post_id ) {   
// verify nonce
if ( !wp_verify_nonce( $_POST['your_meta_box_nonce'], basename(__FILE__) ) ) {
    return $post_id; 
}
// check autosave
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
    return $post_id;
}
// check permissions
if ( 'page' === $_POST['post_type'] ) {
    if ( !current_user_can( 'edit_page', $post_id ) ) {
        return $post_id;
    } elseif ( !current_user_can( 'edit_post', $post_id ) ) {
        return $post_id;
    }  
}

$old = get_post_meta( $post_id, 'your_fields', true );
$new = $_POST['your_fields'];

if ( $new && $new !== $old ) {
    update_post_meta( $post_id, 'your_fields', $new );
} elseif ( '' === $new && $old ) {
    delete_post_meta( $post_id, 'your_fields', $old );
}
}
add_action( 'save_post', 'save_your_fields_meta' );
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,您可以在此处查看https://www.taniarascia.com/wordpress-part- Three-custom-fields-and-metaboxes/ ,这是非常好的链接,它将帮助您逐步创建自定义元框和字段步