是可以在WordPress中提交POST的同时将自动值设置为自定义字段?

当我发布时,我需要这个自定义字段自动采取帖子标题的第一个字母。

示例:如果我的标题是“示例”,则自定义字段值为“e”。

有帮助吗?

解决方案

是这样的。如果您可以使用如下所示的元框添加自定义字段:

// add action to create your custom field
add_action( 'add_meta_boxes', 'create_meta_box'  );
// add a callback that will be called when saving the post
add_filter( 'save_post', 'save_meta_box', 10, 2 );

// function that will create a meta box
function create_meta_box() {
   add_meta_box('sample_meta_box', __('Sample Box'), 'display_meta_box');     
}

// function that will display the actual meta box
function display_meta_box($post, $metabox) {
  ?>
   <input name="sample" type="text" id="sample" value="<?php echo get_post_meta($post->ID, 'sample', true); ?>">
  <?php
}

// function that will be called when the post is saved
function save_meta_box($post_id, $post) {
   // default value for the field
   $value = $_POST['post_title'][0];
   // only use the default value if user haven't specified one
   if(!empty($_POST['sample'])) {
      $value = $_POST['sample'];
   }
   // update the meta data for the post
   update_post_meta($post_id, 'sample', $value);
}
.

当然,您必须在这种情况下更改生成的sample到元数据字段的名称。

如果您已经通过管理界面创建了自定义字段,则可以这样做:

// add a callback that will be called when saving the post
add_filter( 'save_post', 'save_custom_field', 10, 2 ); 

// called when updating a post
function save_custom_field($post_id, $post) {
   // loop through the meta data
   if(isset($_POST['meta'])) {
     foreach($_POST['meta'] as $key => $value) {
        // check if it's the correct field
        if($value['key'] == 'sample') {
           // this will always set the custom field to the first letter in the title
           update_post_meta($post_id, 'sample', $_POST['post_title'][0]);
           break;
        }
     }
   }
}
.

在第一个示例中,您必须将sample更改为自定义字段的名称。

许可以下: CC-BY-SA归因
scroll top